是否有一个通用的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;
}
当前回答
try{
let vari = obj.propTest; // obj may be don't have propTest property
...
} catch(NullException){
// do something here
}
我认为使用try-catch可以避免任何空检查错误,在Angular或JavaScript中也是如此只是捕获空异常并在其中处理。
其他回答
function isEmpty(obj) {
if (typeof obj == 'number') return false;
else if (typeof obj == 'string') return obj.length == 0;
else if (Array.isArray(obj)) return obj.length == 0;
else if (typeof obj == 'object') return obj == null || Object.keys(obj).length == 0;
else if (typeof obj == 'boolean') return false;
else return !obj;
}
在ES6中,使用trim处理空白字符串:
const isEmpty = value => {
if (typeof value === 'number') return false
else if (typeof value === 'string') return value.trim().length === 0
else if (Array.isArray(value)) return value.length === 0
else if (typeof value === 'object') return value == null || Object.keys(value).length === 0
else if (typeof value === 'boolean') return false
else return !value
}
你做得有点过头了。要检查变量是否没有给定值,只需要检查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")) {
我非常喜欢的解决方案:
让我们定义一个空变量为空或未定义,或者如果它有长度,它为零,或者如果是一个对象,它没有键:
function isEmpty (value) {
return (
// null or undefined
(value == null) ||
// has length and it's zero
(value.hasOwnProperty('length') && value.length === 0) ||
// is an Object and has no keys
(value.constructor === Object && Object.keys(value).length === 0)
)
}
退货:
true:undefined,null,“”,[],{}false:true,false,1,0,-1,“foo”,[1,2,3],{foo:1}
检查默认值
function typeOfVar (obj) {
return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
function isVariableHaveDefaltVal(variable) {
if ( typeof(variable) === 'string' ) { // number, boolean, string, object
console.log(' Any data Between single/double Quotes is treated as String ');
return (variable.trim().length === 0) ? true : false;
}else if ( typeof(variable) === 'boolean' ) {
console.log('boolean value with default value \'false\'');
return (variable === false) ? true : false;
}else if ( typeof(variable) === 'undefined' ) {
console.log('EX: var a; variable is created, but has the default value of undefined.');
return true;
}else if ( typeof(variable) === 'number' ) {
console.log('number : '+variable);
return (variable === 0 ) ? true : false;
}else if ( typeof(variable) === 'object' ) {
// -----Object-----
if (typeOfVar(variable) === 'array' && variable.length === 0) {
console.log('\t Object Array with length = ' + [].length); // Object.keys(variable)
return true;
}else if (typeOfVar(variable) === 'string' && variable.length === 0 ) {
console.log('\t Object String with length = ' + variable.length);
return true;
}else if (typeOfVar(variable) === 'boolean' ) {
console.log('\t Object Boolean = ' + variable);
return (variable === false) ? true : false;
}else if (typeOfVar(variable) === 'number' ) {
console.log('\t Object Number = ' + variable);
return (variable === 0 ) ? true : false;
}else if (typeOfVar(variable) === 'regexp' && variable.source.trim().length === 0 ) {
console.log('\t Object Regular Expression : ');
return true;
}else if (variable === null) {
console.log('\t Object null value');
return true;
}
}
return false;
}
var str = "A Basket For Every Occasion";
str = str.replace(/\s/g, "-");
//The "g" flag in the regex will cause all spaces to get replaced.
检查结果:
isVariableHaveDefaltVal(' '); // string
isVariableHaveDefaltVal(false); // boolean
var a;
isVariableHaveDefaltVal(a);
isVariableHaveDefaltVal(0); // number
isVariableHaveDefaltVal(parseInt('')); // NAN isNAN(' '); - true
isVariableHaveDefaltVal(null);
isVariableHaveDefaltVal([]);
isVariableHaveDefaltVal(/ /);
isVariableHaveDefaltVal(new Object(''));
isVariableHaveDefaltVal(new Object(false));
isVariableHaveDefaltVal(new Object(0));
typeOfVar( function() {} );
我使用@Vix函数()来检查哪种类型的对象。
使用instansof«
var prototypes_or_Literals = function (obj) {
switch (typeof(obj)) {
// object prototypes
case 'object':
if (obj instanceof Array)
return '[object Array]';
else if (obj instanceof Date)
return '[object Date]';
else if (obj instanceof RegExp)
return '[object regexp]';
else if (obj instanceof String)
return '[object String]';
else if (obj instanceof Number)
return '[object Number]';
else
return 'object';
// object literals
default:
return typeof(obj);
}
};
output test «
prototypes_or_Literals( '' ) // "string"
prototypes_or_Literals( new String('') ) // "[object String]"
Object.prototype.toString.call("foo bar") //"[object String]"