是否有任何理由將.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
是否有任何理由將.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