是否有一个通用的JavaScript函数来检查变量是否有值,并确保它不是未定义的或空的?我有这个代码,但我不确定它是否涵盖所有情况:

function isEmpty(val){
    return (val === undefined || val == null || val.length <= 0) ? true : false;
}

当前回答

这可能很有用。

数组中的所有值都表示您想要的值(空值、未定义值或其他值),您可以在其中搜索所需的值。

var variablesWhatILookFor = [null, undefined, ''];
variablesWhatILookFor.indexOf(document.DocumentNumberLabel) > -1

其他回答

如果变量尚未声明,则无法使用函数测试未定义,因为会出现错误。

if (foo) {}
function (bar) {}(foo)

如果尚未声明foo,则两者都将生成错误。

如果要测试变量是否已声明,可以使用

typeof foo != "undefined"

如果您想测试foo是否已声明,并且它有一个值,您可以使用

if (typeof foo != "undefined" && foo) {
    //code here
}

看看新的ECMAScript Nullish合并运算符

你可以想到这个功能-??运算符-作为处理null或undefined时“回退”到默认值的一种方式。

let x = foo ?? bar();

同样,上述代码与以下代码等效。

let x = (foo !== null && foo !== undefined) ? foo : bar();

您可能会发现以下函数很有用:

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。作者希望补充他对这个接受王室提升的美好提议的支持。

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
}
try{

     let vari = obj.propTest; // obj may be don't have propTest property

        ...
} catch(NullException){
    // do something here
}

我认为使用try-catch可以避免任何空检查错误,在Angular或JavaScript中也是如此只是捕获空异常并在其中处理。