如何在不更新另一个Javascript对象数组的情况下更新另一个Javascript对象数组 [英] How to update one Javascript object array without updating the other
问题描述
我用一些值创建了一个对象数组.然后,我创建了另一个对象数组,并用第一个对象数组对其进行了初始化.然后,我在第二个数组中推送了一个值,并且控制台记录了两个数组.两个数组具有相同的值.为什么会发生这种情况,我们如何才能阻止这种情况发生?
我的代码:
var a = {"filters":[]};//第一个对象数组var keyValue = {};//在"a"数组中推送2个值keyValue ["abc"] ="123";a.filters.push(keyValue);keyValue ["def"] ="456";a.filters.push(keyValue);var b = a;//创建另一个对象数组&用"a"数组初始化它var keyValue1 = {};//在"b"数组中推送1个值keyValue1 ["ghi"] ="789";b.filters.push(keyValue1);console.log(a);console.log(b);
这将为a和b打印相同的值.
如何在不更新第一个数组的情况下将值推入第二个数组?
对象的赋值(例如 var b = a
)会创建一个对象"b",该对象引用(就像指针一样)相同的位置通常由"a"指向.您可能会发现链接有用.>
但是,您可以使用 slice 方法创建/克隆新数组. var b = a.slice()
I created an object array with some values. Then I created another object array and initialized it with the first one. Then I pushed a value in 2nd array, and console logged both arrays. Both arrays had same value. Why is this happening and how can we stop this?
My Code:
var a = { "filters": [] }; // 1st object array
var keyValue = {};
// pushed 2 values in "a" array
keyValue["abc"] = "123";
a.filters.push(keyValue);
keyValue["def"] = "456";
a.filters.push(keyValue);
var b = a; // created another object array & initialized it with "a" array
var keyValue1 = {};
// pushed 1 value in "b" array
keyValue1["ghi"] = "789";
b.filters.push(keyValue1);
console.log(a);
console.log(b);
This prints same values for a and b.
How do I push values into 2nd array without updating 1st one?
Assignment such as var b = a
for a object creates an object 'b' which references(just like pointer) the same location pointed by 'a', in general. You may find this link helpful.
However you can create/clone a new array with slice method. var b = a.slice()
这篇关于如何在不更新另一个Javascript对象数组的情况下更新另一个Javascript对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!