是否有一个通用的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;
}
当前回答
你做得有点过头了。要检查变量是否没有给定值,只需要检查undefined和null。
function isEmpty(value){
return (typeof value === "undefined" || value === null);
}
这是假设0、“”和对象(甚至是空对象和数组)是有效的“值”。
其他回答
function notEmpty(value){
return (typeof value !== 'undefined' && value.trim().length);
}
它还将检查空格(“”)以及以下内容:
null,未定义,NaN,空,字符串(“”),0,false
这是最安全的支票,我还没有看到它像这样贴在这里:
if (typeof value !== 'undefined' && value) {
//deal with value'
};
它将涵盖从未定义价值的情况,以及以下任何情况:
无效的undefined(未定义的值与从未定义的参数不同)0“”(空字符串)假的NaN公司
已编辑:更改为严格相等(!==),因为这是现在的标准;)
对于每一个有类似问题的人来说,以下内容非常有用,我在过去的几年里都把它放在了我的图书馆里:
(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));
你做得有点过头了。要检查变量是否没有给定值,只需要检查undefined和null。
function isEmpty(value){
return (typeof value === "undefined" || value === null);
}
这是假设0、“”和对象(甚至是空对象和数组)是有效的“值”。
这将检查不确定嵌套的变量是否未定义
function Undef(str)
{
var ary = str.split('.');
var w = window;
for (i in ary) {
try { if (typeof(w = w[ary[i]]) === "undefined") return true; }
catch(e) { return true; }
}
return false;
}
if (!Undef("google.translate.TranslateElement")) {
上面检查Google翻译函数TranslateElement是否存在。这相当于:
if (!(typeof google === "undefined"
|| typeof google.translate === "undefined"
|| typeof google.translate.TranslateElement === "undefined")) {