为什么内联 `push()` 不适用于新创建的数组?

发布于 2025-01-10 03:15:58 字数 856 浏览 2 评论 0原文

我正在创建一个长度为 1,000,000Array 并用 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)

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

泪是无色的血 2025-01-17 03:15:58

根据 MDN, Array#push 返回数组的新长度,而不是数组本身:

返回值
调用该方法的对象的新 length 属性。

您提供的代码可以在任何节点引擎中工作。

According to MDN, Array#push returns the new length of the array, not the array itself:

Return value
The new length property of the object upon which the method was called.

The code you provided works in any node engine otherwise.

羁〃客ぐ 2025-01-17 03:15:58

作为将事物保留在一个分配中的方法的替代方法,您可以将数组分散到一个新数组中:

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

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];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文