链接数组方法和推送的有趣问题 [英] interesting issue with chaining array methods and push

查看:100
本文介绍了链接数组方法和推送的有趣问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前正在搞乱一些数组的东西并发现了一个非常奇怪的警告

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

考虑这段代码:

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

写这篇文章时,我希望得到: 2,4,6,8

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

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

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

和typeof是数字,所以 .join 投掷,因为它不在数量原型。

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

似乎你可以传递/链接任何其他数组方法但不推送。虽然这不是一个问题,如果你将结果传递给一个变量,它的工作原理是什么,为什么会破坏原因,为什么这里返回的是length属性?

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]; 

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

probably another wtfjs moment...

推荐答案


为什么在这里返回长度属性?

Why is the length property being returned here?

它在规范中定义:


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

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?

嗯,你自己已经回答了这个问题: .push 返回没有为数字定义新长度和 .join

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

这篇关于链接数组方法和推送的有趣问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆