【问题标题】:If else shorthand inside array .push()if else 数组中的简写 .push()
【发布时间】:2013-10-15 08:01:48
【问题描述】:

为什么我可以在 .push() 函数中执行 if else shorthand ?喜欢

var arr = [];
arr.push(test||null);
// nothing

但是

var arr = [];
var test = test||null;
arr.push(test);
// [null]

如果变量未定义,我需要插入null

为什么我不能在.push() 函数中使用test||null

【问题讨论】:

  • 您的第一个示例导致错误,这就是为什么没有任何反应。请看一下控制台。

标签: javascript arrays if-statement push array-push


【解决方案1】:
arr.push(typeof(test) == "undefined" ? null: test);

【讨论】:

  • 谢谢,啊,我在寻找更长的版本,但是工作:P
  • 如果您定义测试,您的代码将起作用,就像@MC ND 在他的回答中所说的那样。
  • 这是一个迟到的回复,但typeof 即使没有声明变量也可以工作。
【解决方案2】:

是的。你可以使用

arr.push(test||null);

如果你定义测试。为什么您的第二个代码有效?

var arr = [];
var test = test||null;
arr.push(test);
// [null]

因为你已经定义了 test.

所以,这行得通

var test;
var arr = [];
arr.push(test||null);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-25
    • 2014-09-22
    • 1970-01-01
    • 2014-11-04
    • 2013-11-19
    • 2013-08-18
    • 2011-06-02
    • 1970-01-01
    相关资源
    最近更新 更多