[英]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,000
的Array
,并用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: 根据 MDN ,
Array#push
返回数组的新长度,而不是数组本身:
Return value
返回值
The newlength
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.