为什么内联 `push()` 不适用于新创建的数组?
我正在创建一个长度为 1,000,000
的 Array
并用 1
填充它,如下所示:
const bigArray = Array.from({ length: 1000000 }, () => 1);
当我将新项目推送到该 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)
I am creating an Array
with length of 1,000,000
and filling it with 1
like this:
const bigArray = Array.from({ length: 1000000 }, () => 1);
when I push a new item to that Array
just inline as bellow, Nodejs
logs an error:
// 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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据 MDN, Array#push 返回数组的新长度,而不是数组本身:
您提供的代码可以在任何节点引擎中工作。
According to MDN,
Array#push
returns the new length of the array, not the array itself: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: