更改 Javascript 对象文字中的数组变量
Change array variable inside Javascript object literals
此处提供了以下示例:http://jsfiddle.net/valgaze/se9bmx7t/
大问题:为什么清除数组 "break" 数组与对象字面量中数组引用之间的关系 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
问题:为什么"clearing"数组会破坏对象中数组引用的binding/coupling?
//[...] 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"];
您不是 "clearing" 数组,您是在为变量分配一个新值。原始数组仍然存在(作为另一个对象内的引用),但现在 myArray
指向不同的数组引用。
此处提供了以下示例:http://jsfiddle.net/valgaze/se9bmx7t/
大问题:为什么清除数组 "break" 数组与对象字面量中数组引用之间的关系 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
问题:为什么"clearing"数组会破坏对象中数组引用的binding/coupling?
//[...] 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"];
您不是 "clearing" 数组,您是在为变量分配一个新值。原始数组仍然存在(作为另一个对象内的引用),但现在 myArray
指向不同的数组引用。