有關js的雙向繫結解除方法
阿新 • • 發佈:2020-08-05
最近碰到了一個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}