javascript - 更改 Javascript 对象文字中的数组变量

标签 javascript arrays variables object

此处提供以下示例:http://jsfiddle.net/valgaze/se9bmx7t/

大问题:为什么清除数组会“破坏”Javascript 对象字面量中数组与该数组引用之间的关系?

想象一下,我们有一个存储在变量中的数组,并且我们有一个对象字面量,该对象字面量将对该数组的引用作为对象的属性之一。当我们在数组上使用任何典型的数组方法(push、pop、shift 等)时,对象字面量会用结果更新。类似地,如果我们通过从对象字面量访问它来更新数组,那么数组变量也会被更新。

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

var myArray = ["item1", "item2", "item3"];

var myObject = {key1:"value1", key2:myArray}

//Array is updated, so object is updated
myArray.push("item4"); //Update the array

console.log(myObject.key2); //Object's array updated with new pushed value

//Object is updated, so array is updated
myObject.key2.push("item5"); //myArray is updated with the item5
console.log(myArray); //Array updated with item5

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

    //[...] 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 = ["wiped values"];

最佳答案

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

关于javascript - 更改 Javascript 对象文字中的数组变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29528148/

相关文章:

javascript - Node 流导致大量内存占用或泄漏

c++ - 模板类的特化(数组作为构造函数的输入)?

variables - 如何将变量的值用作变量本身?

javascript - scriptlet 的文本框值

javascript - 从 Node.js 脚本以编程方式调用 npm

javascript - angularjs,具有相同值的嵌套数组中的错误

ios - ios sortedArrayUsingComparator但始终在开头保留一些值

javascript - 在javascript中创建数组的多个副本

java - 当在不同的类中使用时,我的PrintWriter的值变得无效

javascript - Node.js: "process run out of memory"