检查 JavaScript 对象的空子属性

Checking JavaScript object for null subtelty

本文关键字:属性 JavaScript 对象 检查      更新时间:2023-09-26

我相信我已经发现了需要检查javascript对象的undefined和null的情况,如下所示:

if (x !== undefined && x != null && x.length > 0) {...}

但是,在最近升级的 JetBrains 工具中,它告诉我这已经足够了

if (x != undefined && x.length > 0) {...}

我的问题是,我只是想确保字符串"x"的长度为非零,并且不是未定义或空的(测试量最少(。

思潮?

in JavaScript

undefined == null // true
undefined === null // false

因此,与==检查undefined会使==检查null冗余。

检查foo === undefined是否会触发错误 foo 未定义。请参阅变量 === 未定义与变量类型 === "未定义">

CoffeeScript 中的存在运算符编译为

typeof face !== "undefined" && face !== null

编辑:

如果您只想检查字符串,Matt 的评论会更好:

typeof x === 'string' && x.length > 0

尝试

if (x && x.length)

undefinednull0都是假值。

编辑:正如您似乎知道x应该是一个string,您也可以仅使用if (x)作为空字符串也是假的。

您可以使用 Underscore 中的_.isNull JavaScript 库提供了一大堆有用的函数式编程助手。

_.isNull(object(

如果对象的值为 null,则返回 true。

_.isNull(null);
=> true
_.isNull(undefined);
=> false
这是我

使用的,也是最简洁的。 它涵盖:未定义、空、NaN、0、"(空字符串(或假。因此,我们可以说"对象"是真实的。

if(object){
    doSomething();
}

试试这个

 if (!x) {
  // is emtpy
}

要检查nullundefined和"空字符串",您可以编写

if(!x) {
   // will be false for undefined, null and length=0
}

但是你需要确保你的变量是定义的!否则,这将导致错误。

如果要检查object中的值(例如window对象(,则始终可以使用该值。 例如,用于检查localStorage支持:

var supports = {
    localStorage: !!window.localStorage
}