最近碰到了一个bug
var persons = [{ number: 1, age: 11, name: "wanghaha", money: -1 }, { number: 2, age: 12, name: "王一一", money: -3 }, { number: 3, age: 13, name: "王三十", money: 4 }]; var per_con = []; for (var i = persons.length; i > 0; i--) { if (persons[i-1].money > 0) { per_con.push(persons[i-1]); } } console.log("111"+persons); console.log("222"+per_con); var pp = { number: 0, age: 0, name: "", money: 0 }; persons.push(pp); for (var i = persons.length; i > 0; i--) { if (persons[i - 1].number > 2) { persons[i].number += 1; persons[i].age = persons[i - 1].age; persons[i].name = persons[i - 1].name; persons[i].money = persons[i - 1].money; } if (persons[i - 1].number == 2) { persons[i].number = 2; persons[i].age = 100; persons[i].name = "王插队"; persons[i].money = -90; } } console.log("333"+persons); console.log("444"+per_con);
结果:
console.log("111"+persons); 0: {number: 1, age: 11, name: "wanghaha", money: -1} 1: {number: 2, age: 12, name: "王一一", money: -3} 2: {number: 3, age: 13, name: "王三十", money: 4} console.log("222"+per_con); 0: {number: 3, age: 13, name: "王三十", money: 4} console.log("333"+persons); 0: {number: 1, age: 11, name: "wanghaha", money: -1} 1: {number: 2, age: 12, name: "王一一", money: -3} 2: {number: 2, age: 100, name: "王插队", money: -90} 3: {number: 1, age: 13, name: "王三十", money: 4} console.log("444"+per_con); 0: {number: 2, age: 100, name: "王插队", money: -90}
看得出来:per_con的值因为绑定数据发生了变化,相当于只保留了persons[2]
问题出在per_con.push(persons[i-1]);
解决方法1:解除绑定
per_con.push(persons[i-1]);替换成per_con.push(JSON.parse(JSON.stringify(persons[i-1])));
console.log("444"+per_con);
0: {number: 3, age: 13, name: "王三十", money: 4}
解决方法1:替换绑定
function extend(o,p){ for(index in p){ o[index] = p[index]; } return(o); } var persons = [{ number: 1, age: 11, name: "wanghaha", money: -1 }, { number: 2, age: 12, name: "王一一", money: -3 }, { number: 3, age: 13, name: "王三十", money: 4 }]; var per_con = []; for (var i = persons.length; i > 0; i--) { if (persons[i-1].money > 0) { var p = {}; extend(p , persons[i-1]); per_con.push(p); } } console.log("111"+persons); console.log("222"+per_con); var pp = { number: 0, age: 0, name: "", money: 0 }; persons.push(pp); for (var i = persons.length; i > 0; i--) { if (persons[i - 1].number > 2) { persons[i].number += 1; persons[i].age = persons[i - 1].age; persons[i].name = persons[i - 1].name; persons[i].money = persons[i - 1].money; } if (persons[i - 1].number == 2) { persons[i].number = 2; persons[i].age = 100; persons[i].name = "王插队"; persons[i].money = -90; } } console.log("333"+persons); console.log("444"+per_con);
添加替换函数
function extend(o,p){
for(index in p){
o[index] = p[index];
}
return(o);
}
per_con.push(persons[i-1]);替换成
var p = {}; extend(p , persons[i-1]); per_con.push(p);
也成功解决
console.log("444"+per_con);
0: {number: 3, age: 13, name: "王三十", money: 4}