【问题标题】:Check if variable is undefined [duplicate]检查变量是否未定义[重复]
【发布时间】:2018-05-26 00:51:21
【问题描述】:

这两个我都试过了:

如果富 如果 foo[0] == bar.baz[0] input.form-control-success(type="text") 别的 input.form-control-danger(type="text") 别的 输入(类型=“文本”) 除非 foo === 未定义 如果 foo[0] == bar.baz[0] input.form-control-success(type="text") 别的 input.form-control-danger(type="text") 别的 输入(类型=“文本”)

但在这两种情况下我都会遇到错误

无法读取未定义的属性“0”

上线if foo[0] == bar.baz[0]


情况是 foo 有时会传递给 pug,有时不会。

foo 传递时是一个数组,如果传递了我需要根据它的 xth 元素是否与另一个数组的 xth 元素。

【问题讨论】:

  • 尝试if foo !== undefined 而不是if foo

标签: javascript html pug


【解决方案1】:

undefined 在 js 中是假的……看起来 bar.baz 可能是你的罪魁祸首。

【讨论】:

  • 您最初的假设是正确的。您无法在 chrome 中检查这些变量,因为它们是在服务器端编译的
【解决方案2】:

您可以使用typeof 检查变量是否为undefined。它总是返回一个string

if (typeof foo === 'undefined') {
  console.log('foo is undefined');
}

var foo = ['one', 'two', 'three'];

if (typeof foo !== 'undefined') {
  // access elements
  console.log(foo[0] + ', ' + foo[1] + ', ' + foo[2]);
}

【讨论】:

    猜你喜欢
    • 2018-09-09
    • 2016-07-02
    • 2018-05-21
    • 1970-01-01
    • 2010-12-01
    • 2012-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多