链接数组方法和推送的有趣问题
之前在处理一些数组内容时发现了一个非常奇怪的警告,
请考虑以下代码:
[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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它在规范中定义:
好吧,您自己已经回答了这个问题:
.push
返回新的长度,并且.join
没有为数字定义。It is defined in the specification:
Well, you answered this already yourself:
.push
returns the new length and.join
is not defined for numbers.