是否有一个通用的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;
}
当前回答
如果变量尚未声明,则无法使用函数测试未定义,因为会出现错误。
if (foo) {}
function (bar) {}(foo)
如果尚未声明foo,则两者都将生成错误。
如果要测试变量是否已声明,可以使用
typeof foo != "undefined"
如果您想测试foo是否已声明,并且它有一个值,您可以使用
if (typeof foo != "undefined" && foo) {
//code here
}
其他回答
尝试Boolean()和isNaN()(对于数字类型)检查变量是否有值。
函数isEmpty(val){返回类型的val==“number”?isNaN(val):!布尔值(val);}var emptyVals=[未定义,null,false,NaN,''];emptyVals.forEach(v=>console.log(isEmpty(v)));
您可以使用零合并运算符??检查空值和未定义值。参见MDN文档
null ?? 'default string'; // returns "default string"
0 ?? 42; // returns 0
(null || undefined) ?? "foo"; // returns "foo"
第一个评分最好的答案是错误的。若值未定义,则会在现代浏览器中引发异常。您必须使用:
if (typeof(value) !== "undefined" && value)
or
if (typeof value !== "undefined" && value)
对于每一个有类似问题的人来说,以下内容非常有用,我在过去的几年里都把它放在了我的图书馆里:
(function(g3, $, window, document, undefined){
g3.utils = g3.utils || {};
/********************************Function type()********************************
* Returns a lowercase string representation of an object's constructor.
* @module {g3.utils}
* @function {g3.utils.type}
* @public
* @param {Type} 'obj' is any type native, host or custom.
* @return {String} Returns a lowercase string representing the object's
* constructor which is different from word 'object' if they are not custom.
* @reference http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
* http://stackoverflow.com/questions/3215046/differentiating-between-arrays-and-hashes-in-javascript
* http://javascript.info/tutorial/type-detection
*******************************************************************************/
g3.utils.type = function (obj){
if(obj === null)
return 'null';
else if(typeof obj === 'undefined')
return 'undefined';
return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1].toLowerCase();
};
}(window.g3 = window.g3 || {}, jQuery, window, document));
您可以始终使用loadash函数,例如_.isNil或_.isUndefined。它们非常容易使用。