"push()" 方法 returns 数组的长度而不是数组的长度 (JavaScript)

"push()" method returns the length of array instead of array (JavaScript)

我想通过 现有数组 添加一个元素来创建一个新数组 "push() “ 方法。

这是现有数组:

let arr = [{label: 1, value: 1}, {label: 2, value: 2}];

这是我要添加到现有数组的元素:

{label: 3, value: 3}

所以这是使用 "push()" 方法的完整代码:

let arr = [{label: 1, value: 1}, {label: 2, value: 2}];

let newArr = arr.push({label: 3, value: 3});

console.log(newArr); // 3

但是push()方法returns新数组的长度也就是"3 ""newArr" 变量。然而,我真正想要的是 实际的新数组 而不是 它的长度 用于 "newArr" 变量.

有什么方法可以为 "newArr" 变量获取实际的新数组

首先,new关键字在javascript中有指定的作用,不能作为变量名使用。

Reserved keywords in javascript.

其次,push 方法在 就地 起作用,您不必将其分配给新变量。它不会return一个新数组,而是修改原来的数组。

var arr = [{label: 1, value: 1}, {label:2, value:2}];
    arr.push({label:3, value:3});
    
    console.log(arr);

不要使用 const 。只需使用 arr#push 即可。它足以添加数组

var arr= [{label: 1, value: 1}, {label:2, value:2}] 
arr.push({label:3, value:3}) 
 console.log(arr)

学习 JS 的一个很好的参考是 MDN。如果您查看 the Array#push spec,您会发现 它会改变输入数组 ,返回数组的新长度。

使用 push 你实际上是在改变原始数组。不可变数组扩展仅在 ES2015+ 中可用(当前所有主流浏览器都支持)。您可以使用扩展运算符 ...:

const original = [1, 2];
const next = [...original, 3];
console.log(next); // [1, 2, 3]

此外 new 是保留关键字,不能用作标识符。

来自 MDN documentation 推送 returns 数组的新长度,既不是新数组,也不是附加值。

push 函数就地改变了数组,这意味着它将改变原始数组(您实际上不需要重新分配它)!

您可以通过将代码更改为以下方式来获得预期的结果: arr.push({label:3, value:3});

然后分配给一个新数组,如: const newArr = arr;

user7334203, 你写道 arr.push({label:3, value:3}) 意味着你的新对象推入你的数组所以简单地打印你的数组所以你得到了你的数组。

var a = [{label: 1, value: 1}, {label:2, value:2}],
a.push({label:3, value:3}),
var new = a; 
console.log(new)

您可以使用 "concat()" 方法为 "newArr" 获取实际的新数组 =34=] 变量如下:

let arr = [{label: 1, value: 1}, {label: 2, value: 2}];

let newArr = arr.concat({label: 3, value: 3});

console.log(newArr); 
// [
//   {label: 1, value: 1}, 
//   {label: 2, value: 2}, 
//   {label: 3, value: 3}
// ]

此代码不需要 "newArr" 变量。 实际的新数组被分配给原始变量“arr”:

let arr = [{label: 1, value: 1}, {label: 2, value: 2}];

arr = arr.concat({label: 3, value: 3});

console.log(arr);
// [
//   {label: 1, value: 1},
//   {label: 2, value: 2},
//   {label: 3, value: 3}
// ]