Javascript 创建数组并将其推入一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14614134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create array and push into it in one line
提问by mkoryak
The following is just a theoretical JavaScript question. I am curious if the following can be converting into a single statement:
以下只是一个理论上的 JavaScript 问题。我很好奇以下内容是否可以转换为单个语句:
if(!window.foo){
window.foo = [];
}
window.foo.push('bar');
everyone has probably written this code before, but can it be done in one line?
At first I thought something like this would work:
这段代码大家可能以前都写过,但是能不能一行写完呢?
起初我认为这样的事情会起作用:
(window.foo || window.foo = []).push('bar');
but that doesn't work because of an invalid assignment. Next I tried chaining something on the push, but that doesn't work because push does not return the array.
但这不起作用,因为分配无效。接下来我尝试在 push 上链接一些东西,但这不起作用,因为 push 不返回数组。
Any thoughts on if this can be done in plain JavaScript?
(the result by the way should be that window.foo = ['bar'])
关于这是否可以用纯 JavaScript 完成的任何想法?
(顺便说一下,结果应该是这样window.foo = ['bar'])
回答by zzzzBov
You've got your assignment backwards*. It should be:
你的作业倒退了*。它应该是:
(window.foo = window.foo || []).push('bar');
The ||operator in JavaScript does not return a boolean value. If the left hand side is truthy, it returns the left hand side, otherwise it returns the right hand side.
||JavaScript中的运算符不返回布尔值。如果左侧为真,则返回左侧,否则返回右侧。
a = a || [];
is equivalent to
相当于
a = a ? a : [];
So an alternative way of writing the above is:
因此,编写上述内容的另一种方法是:
(window.foo = window.foo ? window.foo : []).push('bar');
* see comments for details
* 详情见评论
回答by Guffa
Your code works just fine if you add parentheses so that it does what you intended:
如果您添加括号,您的代码就可以正常工作,以便它按照您的意图执行:
(window.foo || (window.foo = [])).push('bar');
Without the parentheses, it thinks that it should evaluate window.foo || window.foofirst, and then assign the array to the result of that, which is not possible.
没有括号,它认为应该window.foo || window.foo先求值,然后将数组赋值给那个结果,这是不可能的。
回答by Plynx
This question got me playing with different options for fun. It's too bad pushreturns the length instead of the original array reference, but for even shorter expressions it can be helpful to have something that can be immediately iterated, mapped, etc.
这个问题让我玩了不同的选择来获得乐趣。push返回长度而不是原始数组引用太糟糕了,但是对于更短的表达式,拥有可以立即迭代、映射等的东西会很有帮助。
window.foo = (window.foo||[]).concat(['bar']); // always returns array, allowing:
(window.foo = (window.foo||[]).concat(['bar'])).forEach( ... )
(window.foo = window.foo||[]).push('bar'); // always returns length
window.foo && window.foo.push('bar') || (window.foo = ['bar']); // playing around

