为什么Array.prototype.push返回新的长度而不是更有用的东西? [英] Why does Array.prototype.push return the new length instead of something more useful?

查看:215
本文介绍了为什么Array.prototype.push返回新的长度而不是更有用的东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ECMA-262,第3版 Array.prototype.push 方法的返回值是 Number


15.4.4.7 Array.prototype.push([item1 [,item2 [,...]] ]])

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

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.

设计决策是什么返回数组的新长度,而不是返回可能更有用的东西,例如:

What were the design decisions behind returning the array's new length, as opposed to returning something potentially more useful, like:


  • 对新附加项的引用/

  • 变异数组本身

为什么这样做,并且有历史记录这些决定是如何做出的?

Why was it done like this, and is there a historical record of how these decisions came to be made?

推荐答案

我无法解释为什么他们选择返回新的长度,但是为了回应您的建议:

I cannot explain why they chose to return the new length, but in response to your suggestions:


  • 返回新添加的项目:

鉴于JavaScript使用C样式赋值来发出指定值(而不是基本样式赋值),你仍然可以有这种行为:

Given that JavaScript uses C-style assignment which emits the assigned value (as opposed to Basic-style assignment which does not) you can still have that behavior:

var addedItem;
myArray.push( addedItem = someExpression() );

(虽然我知道这确实意味着你不能将它作为r值的一部分声明+赋值组合)

(though I recognise this does mean you can't have it as part of an r-value in a declaration+assignment combination)


  • 返回变异数组本身:

这将是流利API的风格,在ECMAScript 3完成后显着获得了普及,并且它不会保留ECMAScript中其他库功能的风格,并且它不是通过创建自己的推送方法来启用您所关注的场景需要更多额外的工作:

That would be in the style of "fluent" APIs which gained popularity significantly after ECMAScript 3 was completed and it would not be keeping in the style of other library features in ECMAScript, and again, it isn't that much extra legwork to enable the scenarios you're after by creating your own push method:

Array.prototype.push2 = function(x) {
    this.push(x);
    return this;
};

myArray.push2( foo ).push2( bar ).push2( baz );

或:

Array.prototype.push3 = function(x) {
    this.push(x);
    return x;
};

var foo = myArray.push3( computeFoo() );

这篇关于为什么Array.prototype.push返回新的长度而不是更有用的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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