简体   繁体   English

为什么内联 `push()` 对新创建的数组不起作用?

[英]why inline `push()` doesn't work on new created array?

I am creating an Array with length of 1,000,000 and filling it with 1 like this:我正在创建一个长度为1,000,000Array ,并用1填充它,如下所示:

const bigArray = Array.from({ length: 1000000 }, () => 1);

when I push a new item to that Array just inline as bellow, Nodejs logs an error:当我将一个新项目推送到该Array时,就像下面那样内联, Nodejs记录一个错误:

 // This rise an TypeError: bigArray.push is not a function const bigArray = Array.from({ length: 1000000 }, () => 1).push(3);

 // Although this one works right const bigArray = Array.from({ length: 1000000 }, () => 1); bigArray.push(3)

在此处输入图像描述

According to MDN , Array#push returns the new length of the array, not the array itself: 根据 MDNArray#push返回数组的新长度,而不是数组本身:

Return value返回值
The new length property of the object upon which the method was called.调用该方法的 object 的新length属性。

The code you provided works in any node engine otherwise.否则,您提供的代码可以在任何节点引擎中使用。

As an alternative to that approach to keep things in one assignment, you could spread the array into a new array:作为将事物保留在一个分配中的方法的替代方法,您可以将数组扩展到一个新数组中:

const bigArray = [...Array.from({ length: 1000000 }, () => 1), 3];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM