创建数组并将其推入一行 [英] Create array and push into it in one line

查看:98
本文介绍了创建数组并将其推入一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下只是一个理论上的JavaScript问题。我很好奇以下是否可以转换成单个语句:

The following is just a theoretical JavaScript question. I am curious if the following can be converting into a single statement:

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

但由于分配无效,这不起作用。接下来我尝试在推送上链接某些内容,但这不起作用,因为push不会返回数组。

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.

关于是否可以用普通的JavaScript完成任何想法?

(顺便说一句,结果应该是窗口.foo = ['bar']

Any thoughts on if this can be done in plain JavaScript?
(the result by the way should be that window.foo = ['bar'])

推荐答案

你的作业已向后*。它应该是:

You've got your assignment backwards*. It should be:

(window.foo = window.foo || []).push('bar');

JavaScript || 运算符>不返回布尔值。如果左侧是真实的,它将返回左侧,否则它将返回右侧。

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.

a = a || [];

相当于

a = a ? a : [];

所以另外一种写作方式是:

So an alternative way of writing the above is:

(window.foo = window.foo ? window.foo : []).push('bar');

*详见评论

这篇关于创建数组并将其推入一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆