Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

javascript - Array.push return pushed value?

Are there any substantial reasons why modifying Array.push() to return the object pushed rather than the length of the new array might be a bad idea?

I don't know if this has already been proposed or asked before; Google searches returned only a myriad number of questions related to the current functionality of Array.push().

Here's an example implementation of this functionality, feel free to correct it:

;(function() {
    var _push = Array.prototype.push;
    Array.prototype.push = function() {
        return this[_push.apply(this, arguments) - 1];
    }
}());

You would then be able to do something like this:

var someArray = [],
    value = "hello world";

function someFunction(value, obj) {
    obj["someKey"] = value;
}

someFunction(value, someArray.push({}));

Where someFunction modifies the object passed in as the second parameter, for example. Now the contents of someArray are [{"someKey": "hello world"}].

Are there any drawbacks to this approach?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

See my detailed answer here

TLDR;
You can get the return value of the mutated array, when you instead add an element using array.concat[].

concat is a way of "adding" or "joining" two arrays together. The awesome thing about this method, is that it has a return value of the resultant array, so it can be chained.

newArray = oldArray.concat[newItem];

This also allows you to chain functions together

updatedArray = oldArray.filter((item) => { item.id !== updatedItem.id).concat[updatedItem]};

Where item = {id: someID, value: someUpdatedValue}

The main thing to notice is, that you need to pass an array to concat.
So make sure that you put your value to be "pushed" inside a couple of square brackets, and you're good to go.
This will give you the functionality you expected from push()

You can use the + operator to "add" two arrays together, or by passing the arrays to join as parameters to concat().

let arrayAB = arrayA + arrayB;
let arrayCD = concat(arrayC, arrayD);

Note that by using the concat method, you can take advantage of "chaining" commands before and after concat.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...