我相信我已经找到了需要检查 javascript 对象的 undefined 和 null 的情况,如下所示:
if (x !== undefined && x != null && x.length > 0) {...}
但是,在最近的 JetBrains 工具升级中,它告诉我这已经足够了
if (x != undefined && x.length > 0) {...}
我的问题是,我只是想确保字符串“x”的长度为非零并且不是未定义或 null(使用最少的测试)。
想法?
我相信我已经找到了需要检查 javascript 对象的 undefined 和 null 的情况,如下所示:
if (x !== undefined && x != null && x.length > 0) {...}
但是,在最近的 JetBrains 工具升级中,它告诉我这已经足够了
if (x != undefined && x.length > 0) {...}
我的问题是,我只是想确保字符串“x”的长度为非零并且不是未定义或 null(使用最少的测试)。
想法?
在javascript中
undefined == null // true
undefined === null // false
因此检查==forundefined会使==检查变得null多余。
检查是否foo === undefined会触发错误foo is not defined。请参阅变量 === 未定义与 typeof 变量 === “未定义”
CoffeeScript 中的存在运算符编译为
typeof face !== "undefined" && face !== null
编辑:
如果您只想检查字符串,Matt 的评论会更好:
typeof x === 'string' && x.length > 0
尝试
if (x && x.length)
和undefined都是null假0值。
编辑:您似乎知道x应该是 a string,您也可以只if (x)用作空字符串也是虚假的。
你可以_.isNull从Underscore使用一个 JavaScript 库,它提供了一大堆有用的函数式编程助手。
_.isNull(对象)
如果 object 的值为 null,则返回 true。
_.isNull(null);
=> true
_.isNull(undefined);
=> false
这是我用的,也是最简洁的。它涵盖:undefined、null、NaN、0、“”(空字符串)或 false。因此,我们可以说“对象”是真实的。
if(object){
doSomething();
}
尝试这个
if (!x) {
// is emtpy
}
要检查nullAND undefinedAND “空字符串”,你可以写
if(!x) {
// will be false for undefined, null and length=0
}
但是您需要确保您的变量已定义!否则这将导致错误。
如果您正在检查一个object(例如window对象)中的值,您可以随时使用它。例如检查localStorage支持:
var supports = {
localStorage: !!window.localStorage
}