Why does Array.prototype.push return the new length instead of something more useful?

后端 未结 4 1876
悲哀的现实
悲哀的现实 2020-12-15 19:49

Ever since its introduction in ECMA-262, 3rd Edition, the Array.prototype.push method\'s return value is a Number:

4条回答
  •  盖世英雄少女心
    2020-12-15 20:14

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

    • Returning the newly appended item:

    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() );
    

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

    • Returning the mutated array itself:

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

    or:

    Array.prototype.push3 = function(x) {
        this.push(x);
        return x;
    };
    
    var foo = myArray.push3( computeFoo() );
    

提交回复
热议问题