更改Javascript对象文本中的数组变量

更改Javascript对象文本中的数组变量,javascript,arrays,variables,object,Javascript,Arrays,Variables,Object,此处提供了以下示例: 大问题:为什么清除数组会“破坏”Javascript中对象文本中数组和该数组引用之间的关系 假设我们有一个数组存储在一个变量中,我们有一个对象文本,引用该数组作为对象的属性之一。当我们在数组上使用任何典型的数组方法(push、pop、shift等)时,对象文本会随着结果而更新。同样,如果我们通过从对象文本访问来更新数组,那么数组变量也会更新 例如,更新对象会更新数组(反之亦然) 问题:为什么“清除”数组会破坏对象中数组引用的绑定/耦合? //[...] contin

此处提供了以下示例:

大问题:为什么清除数组会“破坏”Javascript中对象文本中数组和该数组引用之间的关系

假设我们有一个数组存储在一个变量中,我们有一个对象文本,引用该数组作为对象的属性之一。当我们在数组上使用任何典型的数组方法(push、pop、shift等)时,对象文本会随着结果而更新。同样,如果我们通过从对象文本访问来更新数组,那么数组变量也会更新

例如,更新对象会更新数组(反之亦然)

问题:为什么“清除”数组会破坏对象中数组引用的绑定/耦合?

    //[...] continued from first block above

    myArray = ["muahahah, everything is wiped out"];
    console.log("myArray", myArray); //Returns ["muahahah, everything is wiped out"]
    console.log("myObject.key2", myObject.key2); //Returns the original items 1-5 

    //If we clear out the array via the object, the array does get updated
    myObject.key2 = ["cleared the array from object"];
    console.log("myArray", myArray); //returns ["cleared array"]
    console.log("myObject.key2", myObject.key2); //returns ["cleared array"]

像这样操作数组肯定有什么问题:myArray=[“擦除的值”]

您不是在“清除”数组,而是在为变量赋值。原始数组仍然存在(作为另一个对象内的引用),但现在
myArray
指向另一个数组引用。

您通过指定一个新对象(数组)而不是操作现有对象(数组)打破了引用可能的重复项
    //[...] continued from first block above

    myArray = ["muahahah, everything is wiped out"];
    console.log("myArray", myArray); //Returns ["muahahah, everything is wiped out"]
    console.log("myObject.key2", myObject.key2); //Returns the original items 1-5 

    //If we clear out the array via the object, the array does get updated
    myObject.key2 = ["cleared the array from object"];
    console.log("myArray", myArray); //returns ["cleared array"]
    console.log("myObject.key2", myObject.key2); //returns ["cleared array"]