链接数组方法和推送的有趣问题

发布于 2024-12-08 15:33:16 字数 771 浏览 3 评论 0原文

之前在处理一些数组内容时发现了一个非常奇怪的警告,

请考虑以下代码:

[1,2,3].map(function(el) { return el * 2}).push(4*2)。 join(" ");

在编写它时,我期望得到:2, 4, 6, 8

相反,它抛出了异常。在进一步调查中, .push 返回传递数组的调整后的 .length

[1,2,3].map(function(el) { return el * 2}).push(4*2);
>>> 4

[1,2,3,4].map(function(el) { return el * 2}).push("hi");
>>> 5

并且 typeof 是数字,因此 .join 抛出异常不在数字原型中。

看来您可以传递/链接任何其他数组方法,但不能推送。虽然这不是问题,并且如果将结果传递到变量中它就可以工作,但为什么会按原样中断以及为什么会在此处返回 length 属性?

这工作正常...

var foo = [1,2,3,4].map(function(el) { return el * 2});
foo.push(5*2);
console.log(foo); 
>>> [2, 4, 6, 8, 10]; 

可能是另一个 wtfjs 时刻...

Was messing around with some array stuff earlier and discovered a very peculiar caveat

consider this code:

[1,2,3].map(function(el) { return el * 2}).push(4*2).join(" ");

In writing it, I expected to get: 2, 4, 6, 8

instead, it threw an exception. in investigating further, the .push returns the adjusted .length of the passed array:

[1,2,3].map(function(el) { return el * 2}).push(4*2);
>>> 4

[1,2,3,4].map(function(el) { return el * 2}).push("hi");
>>> 5

and typeof is number, so the .join throws as it's not in the number proto.

it seems you can pass on / chain any other array methods but not push. though this is not a problem and it works if you pass on the result into a variable, why is breaking as is and why is the length property being returned here?

this works fine...

var foo = [1,2,3,4].map(function(el) { return el * 2});
foo.push(5*2);
console.log(foo); 
>>> [2, 4, 6, 8, 10]; 

probably another wtfjs moment...

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

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

发布评论

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

评论(1

世态炎凉 2024-12-15 15:33:16

为什么这里返回 length 属性?

它在规范中定义:

参数按照它们出现的顺序附加到数组的末尾。数组的新长度作为调用结果返回。

 

为什么会破坏?

好吧,您自己已经回答了这个问题: .push 返回新的长度,并且 .join 没有为数字定义。

Why is the length property being returned here?

It is defined in the specification:

The arguments are appended to the end of the array, in the order in which they appear. The new length of the array is returned as the result of the call.

 

Why is breaking as is?

Well, you answered this already yourself: .push returns the new length and .join is not defined for numbers.

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