Array.push()与对象
问题描述:
是否有任何理由将.push()对象放入数组中?下面的简单例子。Array.push()与对象
let myArray = [{x:1},{x:2}];
let myObj = {x:1};
let x = myArray.push(myObj);
console.log(x)
//我'期待[{X:1},{X:2},{X:1}],但我得到3
答
简单,推只是返回新的长度数组和数组已被修改。尝试:
console.log(myArray)
答
的push
返回值是修改后的数组的长度。它不是对同一个数组的另一个引用,也不是一个新数组。
如果你想记录数组,然后console.log(myArray)
而不是x
。
答
你应该console.log(myArray);你这样做的方式返回该数组的新长度,并为其分配另一个参考
DEMO
let myArray = [{x:1},{x:2}];
let myObj = {x:1};
console.log(myArray);
myArray.push(myObj);
console.log(myArray);
答
的Array.push()函数工作正常,并返回新的长度的阵列
push()方法将一个或多个元素添加到数组的末尾并返回数组的新长度。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push?v=a
阵列#推返回数组,它分配给'x'的新长度。尝试'console.log(myArray)' –
你需要'console.log(myArray)'来得到你所期待的。 – cometguy