以下是我的简化案例:
var a = {
filters: ["aa"]
}
var b = {
filters:["bb","bbb"]
}
var ab = {
}
$.extend(ab, a);
console.log(JSON.stringify(a)); //{"filters":["aa"]}
console.log(JSON.stringify(ab)); //{"filters":["aa"]}
for (var i = 0; i < b.filters.length; i++){
ab.filters.push(b.filters[i]); //it only inserts to 'ab', but why 'a' also has it?
}
console.log(JSON.stringify(a)); //{"filters":["aa","bb","bbb"]} -> it should be only "aa", shouldn't it??
console.log(JSON.stringify(ab)); //{"filters":["aa","bb","bbb"]}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
如您所见,我将a
对象扩展为ab
对象。然后,我将b
对象的值插入ab
对象。不知何故,a
对象还具有b
对象的值。
是否有任何解决方案可以阻止b
对象将其值插入a
对象?
答案 0 :(得分:2)
您需要将true
作为$.extend
的第一个参数传递原始对象的深层副本:
var a = { filters: ["aa"] }
var b = { filters: ["bb", "bbb"] }
var ab = {}
$.extend(true, ab, a); // < note true here
console.log(JSON.stringify(a)); // {"filters":["aa"]}
console.log(JSON.stringify(ab)); // {"filters":["aa"]}
for (var i = 0; i < b.filters.length; i++) {
ab.filters.push(b.filters[i]);
}
console.log(JSON.stringify(a)); // {"filters":["aa"]}
console.log(JSON.stringify(ab)); // {"filters":["aa","bb","bbb"]}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
答案 1 :(得分:0)
答案 2 :(得分:0)