Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript-检查未定义和Null的通用函数_Javascript - Fatal编程技术网

JavaScript-检查未定义和Null的通用函数

JavaScript-检查未定义和Null的通用函数,javascript,Javascript,我的脚本中有很多变量,每个变量都可能包含一个未定义或空的值 我注意到很多重复代码检查未定义和空值,可以创建一个公共函数吗 我创建了一个通用函数,用于检查所有变量是否未定义或为空: JS原件: var testa; var testb; var testc; if ((typeof testa == "undefined" || testa == null) && (typeof testa == "undefined" || testb == null) &&

我的脚本中有很多变量,每个变量都可能包含一个未定义或空的值

我注意到很多重复代码检查未定义和空值,可以创建一个公共函数吗

我创建了一个通用函数,用于检查所有变量是否未定义或为空:

JS原件:

var testa;
var testb;
var testc;

if ((typeof testa == "undefined" || testa == null) && (typeof testa == "undefined" || testb == null) && (typeof testc == "undefined" || testc == null)) {
    //Do something ///////////
}
新的:

var testa;
var testb;
var testc;

if (checkValues(testa) && checkValues(testb) && checkValues(testc)) {
    //Do something ///////////
}

function checkValues (v) {
    return (v == "undefined") || (v == null);
}
这很有效。但是,如果testa包含一个值,并且testb和testc为null或未定义,该怎么办?e、 g:

if ((typeof testa == "undefined" || testa == null) && (typeof testa != "undefined" || testb != null) && (typeof testc != "undefined" || testc != null)) {
    //Do something ///////////
}

这取决于您的使用情况,根据您给定的条件,如果testa包含一个值,并且testb和testc为null或未定义,则根据您的条件,它将返回false。

您不需要函数来执行此操作。==对于未定义值和null值,null都为true,因此您只需要:

if (testa == null && testb == null && testc == null)

我假设您不想处理未声明的变量,对于这些变量,您需要类型为…==未定义的测试,并且无法使用帮助函数,请参见

,然后它将不会进入if块,因为您正在使用and条件。检查值可能会出现许多问题。推荐阅读:此外,您还可以执行类似函数isUndefOrNullx{return x==null | | x==undefined;}在比较null时注意“==”和“==”之间的差异。还有,计数中的'Nan'不是未定义的,也不是空的,您可能也想检查它。检查'Nan'很棘手,顺便说一下,您忘记了checkValues函数中的关键字typeof。它当前正在查找字符串。