简体   繁体   中英

How to use Array.push and return the pushed item?

I am calling return someArr[someArr.push(newItem)-1]; and it does pretty what it should.

Wondering is there a syntactic "sugar" for that extremely common operation? I wonder because returned new length is indeed more rarely needed, than actual constructed object (which caller definetely may want to polulate). Or is that made because it actually will return "a copy of an object", and my edits to its fields "will not survive" in actual tree?

Just like a JS <= 1.2 did: return someArr.push(newItem);

Just want to know - Is there are new "replacement" method, that I am unaware of?


Also I had a minor subquestion "does that return an 'independent' copy of an object or a 'reference' to actual object?" but simple fiddle by @PatricRoberts just figured out that it is actually a reference (as it was expected), so I've credited him, for his assistance!

You could also do it using a logical and (&&) .

return someArr.push(newItem) && newItem;

Since the array length will be positive after the push, the right-most expression will be evaluated and its value returned.

This syntax is less clear than @adiga's answer using the comma operator though.

However, I personally prefer to return the new item on a new line to make it more readable :

someArr.push(newItem);
return newItem;

You could use the comma operator :

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.

Like this:

return (someArr.push(newItem), newItem)

This is equivalent to:

someArr.push(newItem);
return newItem

You can do this by returning an assignment to the index of the current .length .

return someArr[someArr.length] = newItem;

The result of the assignment is the item being assigned, so that's what will be returned.

Assigning to the current .length of the array automatically expands it. Note that assigning to any index higher than the current .length will leave holes in the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM