是否有一个通用的JavaScript函数来检查变量是否有值,并确保它不是未定义的或空的?我有这个代码,但我不确定它是否涵盖所有情况:
function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}
是否有一个通用的JavaScript函数来检查变量是否有值,并确保它不是未定义的或空的?我有这个代码,但我不确定它是否涵盖所有情况:
function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}
当前回答
您可能会发现以下函数很有用:
function typeOf(obj) {
return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
或在ES7中(如有进一步改进,请发表评论)
function typeOf(obj) {
const { toString } = Object.prototype;
const stringified = obj::toString();
const type = stringified.split(' ')[1].slice(0, -1);
return type.toLowerCase();
}
结果:
typeOf(); //undefined
typeOf(null); //null
typeOf(NaN); //number
typeOf(5); //number
typeOf({}); //object
typeOf([]); //array
typeOf(''); //string
typeOf(function () {}); //function
typeOf(/a/) //regexp
typeOf(new Date()) //date
typeOf(new WeakMap()) //weakmap
typeOf(new Map()) //map
“请注意,绑定运算符(::)根本不是ES2016(ES7)的一部分,也不是ECMAScript标准的任何后续版本。它目前是引入语言的第0阶段(strawman)建议。”–Simon Kjellberg。作者希望补充他对这个接受王室提升的美好提议的支持。
其他回答
看看新的ECMAScript Nullish合并运算符
你可以想到这个功能-??运算符-作为处理null或undefined时“回退”到默认值的一种方式。
let x = foo ?? bar();
同样,上述代码与以下代码等效。
let x = (foo !== null && foo !== undefined) ? foo : bar();
try{
let vari = obj.propTest; // obj may be don't have propTest property
...
} catch(NullException){
// do something here
}
我认为使用try-catch可以避免任何空检查错误,在Angular或JavaScript中也是如此只是捕获空异常并在其中处理。
var myNewValue = myObject && myObject.child && myObject.child.myValue;
这永远不会抛出错误。如果myObject、child或myValue为空,则myNewValue将为空。不会引发任何错误
我想这会让你的代码看起来更简单
检查变量是否未定义或为空
var a=undefined, b=null, c='hello world', d;
if(a !== (a ?? {})) { /**/ } // true
if(b !== (b ?? {})) { /**/ } // true
if(c !== (c ?? {})) { /**/ } // false
if(d !== (d ?? {})) { /**/ } // true
检查变量是否未定义或为空
var a=undefined, b=null, c='hello world', d;
if(a === (a ?? {})) { /**/ } // false
if(b === (b ?? {})) { /**/ } // false
if(c === (c ?? {})) { /**/ } // true
if(d === (d ?? {})) { /**/ } // false
这是最安全的支票,我还没有看到它像这样贴在这里:
if (typeof value !== 'undefined' && value) {
//deal with value'
};
它将涵盖从未定义价值的情况,以及以下任何情况:
无效的undefined(未定义的值与从未定义的参数不同)0“”(空字符串)假的NaN公司
已编辑:更改为严格相等(!==),因为这是现在的标准;)