简体   繁体   English

如何使用 Array.push 并返回推送的项目?

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

I am calling return someArr[someArr.push(newItem)-1];我打电话给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).我想知道因为返回的新length确实比实际构造的对象(调用者可能想要填充)更不需要。 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);就像 JS <= 1.2 所做的一样: 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!但是@PatricRoberts 的简单小提琴才发现它实际上是一个参考(正如预期的那样),所以我感谢他的帮助!

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.不过,这种语法不如@adiga 使用逗号运算符的答案清晰。

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 .您可以通过返回对当前.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.分配给数组的当前.length自动扩展它。 Note that assigning to any index higher than the current .length will leave holes in the array.请注意,分配给任何高于当前.length索引都会在数组中留下漏洞。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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