是否有一个通用的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 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]"
其他回答
看看新的ECMAScript Nullish合并运算符
你可以想到这个功能-??运算符-作为处理null或undefined时“回退”到默认值的一种方式。
let x = foo ?? bar();
同样,上述代码与以下代码等效。
let x = (foo !== null && foo !== undefined) ? foo : bar();
仅使用“空值合并”检查未定义和空值
if ((myVariable ?? undefined) !== undefined) {
// handle myVariable has a value, including 0 or ""
}
else {
// handle undefined or null only
}
来自铬控制台
{const x=undefined; (x ?? undefined) !== undefined}
false
{const x=null; (x ?? undefined) !== undefined}
false
{const x=0; (x ?? undefined) !== undefined}
true
{const x=""; (x ?? undefined) !== undefined}
true
{const x={}; (x ?? undefined) !== undefined}
true
{const x=[]; (x ?? undefined) !== undefined}
true
{const x="a"; (x ?? undefined) !== undefined}
true
仅对未定义和null返回false:
返回值??假的
这里是我的-如果值为null、undefined等或空白(即仅包含空格),则返回true:
function stringIsEmpty(value) {
return value ? value.trim().length == 0 : true;
}
尝试Boolean()和isNaN()(对于数字类型)检查变量是否有值。
函数isEmpty(val){返回类型的val==“number”?isNaN(val):!布尔值(val);}var emptyVals=[未定义,null,false,NaN,''];emptyVals.forEach(v=>console.log(isEmpty(v)));