這裏是我的簡單情況:如何在AB對象中插入另一個值時將對象擴展爲AB對象,而不影響對象?
var a = {
\t filters: ["aa"]
}
var b = {
\t 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++){
\t 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"]}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
正如你所看到的,我的a
對象擴展到ab
對象。之後,我將b
對象的值插入到ab
對象中。不知何故,a
對象也有b
對象的值。
是否有解決方案阻止b
對象也將其值插入到a
對象?
你需要做一個*深*副本,這'$ .extend()'不做。 – Pointy
@Pointly:http://api.jquery.com/jQuery.extend/#jQuery-extend-deep-target-object1-objectN –
@RoryMcCrossan哦,沒錯。那麼對於OP來說多好啊:) – Pointy