`push`方法返回一个数字而不是一个数组 [英] `push` method returns a number and not an array

查看:53
本文介绍了`push`方法返回一个数字而不是一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 push 方法构造一个数组.我有一个这样的对象数组:

I want to construct an array using the push method. I have an array of objects like this:

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

我想添加另一个像这样的元素:

I want to add another element like this:

{ label: 3, value: 3 }

所以我在写

const new = arr.push({ label: 3, value: 3 });

,它向我显示了一个数字,该数字为 3 .但是我想要实际的数组,而不是它的长度.

and it shows me a number which is 3. But I want the actual array, not its length.

推荐答案

首先, new 关键字在javascript中具有指定的作用,您不能将其用作变量名.

First of all, the new keyword has a specified role in javascript, you can't use it as a variable name.

在javascript中保留的关键字.

第二, push 方法在原地 起作用,您不必将其分配给新变量.它不会返回新数组,但会修改原始数组.

Secondly, push method works in situ, you don't have to assign it to a new variable. It won't return a new array, but modify the original one.

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

这篇关于`push`方法返回一个数字而不是一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆