如何在JavaScript中检查空值?我写了下面的代码,但没用。

if (pass == null || cpass == null || email == null || cemail == null || user == null) {      

    alert("fill all columns");
    return false;  

}   

如何在JavaScript程序中查找错误?


当前回答

首先,您有一个没有函数体的return语句。这很可能会引发错误。

一个更干净的检查方法是简单地使用!操作员:

if (!pass || !cpass || !email || !cemail || !user) {

    alert("fill all columns");

}

其他回答

要检查空值,请使用以下命令:

if (variable === null)

此测试仅通过null,不通过“”、undefined、false、0或NaN。

此外,我还为每个“类假”值提供了绝对检查(对于!变量返回true)。

注意,对于某些绝对检查,您需要使用绝对等于:==和typeof。

我在这里创建了一个JSFiddle,以显示所有单独测试的工作情况

以下是每次检查的输出:

Null Test:

if (variable === null)

- variable = ""; (false) typeof variable = string

- variable = null; (true) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (false) typeof variable = number



Empty String Test:

if (variable === '')

- variable = ''; (true) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (false) typeof variable = number




Undefined Test:

if (typeof variable == "undefined")

-- or --

if (variable === undefined)

- variable = ''; (false) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (true) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (false) typeof variable = number



False Test:

if (variable === false)

- variable = ''; (false) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (true) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (false) typeof variable = number



Zero Test:

if (variable === 0)

- variable = ''; (false) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (true) typeof variable = number

- variable = NaN; (false) typeof variable = number



NaN Test:

if (typeof variable == 'number' && !parseFloat(variable) && variable !== 0)

-- or --

if (isNaN(variable))

- variable = ''; (false) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (true) typeof variable = number

正如你所看到的,测试NaN有点困难;

JAVASCRIPT中的AFAIK当变量已声明但未赋值时,其类型未定义。所以我们可以检查变量,即使它是一个持有某个实例代替值的对象。

创建一个用于检查返回true的无效性的助手方法,并在API中使用它。

检查变量是否为空的helper函数:

function isEmpty(item){
    if(item){
        return false;
    }else{
        return true;
    }
}

尝试捕获异常API调用:

try {

    var pass, cpass, email, cemail, user; // only declared but contains nothing.

    // parametrs checking
    if(isEmpty(pass) || isEmpty(cpass) || isEmpty(email) || isEmpty(cemail) || isEmpty(user)){
        console.log("One or More of these parameter contains no vlaue. [pass] and-or [cpass] and-or [email] and-or [cemail] and-or [user]");
    }else{
        // do stuff
    }

} catch (e) {
    if (e instanceof ReferenceError) {
        console.log(e.message); // debugging purpose
        return true;
    } else {
        console.log(e.message); // debugging purpose
        return true;
    }
}

一些测试用例:

var item = ""; // isEmpty? true
var item = " "; // isEmpty? false
var item; // isEmpty? true
var item = 0; // isEmpty? true
var item = 1; // isEmpty? false
var item = "AAAAA"; // isEmpty? false
var item = NaN; // isEmpty? true
var item = null; // isEmpty? true
var item = undefined; // isEmpty? true

console.log("isEmpty? "+isEmpty(item));

“Object.is()”方法可用于确定两个值是否相同。因此,您可以使用它来检查对象是否为空。

检查空值

let testA = null; //null
console.log(Object.is(testA, null)); //true //null === null

if(Object.is(testA, null)) {
  console.log("This is a Null Value");
}
Output:
true
This is a Null Value

检查未定义的值

let testB; //undefined
console.log(Object.is(testB, undefined)); //true //undefined === undefined

if(Object.is(testB, undefined)) {
  console.log("This is an undefined Value");
}
Output:
true
This is an undefined Value

如果要同时检查undefined和null,请使用此选项。

let testC; //undefined
console.log(Object.is(testC, undefined)); //true //undefined === undefined
console.log(Object.is(testC, null)); //false //undefined === null

if (Object.is(testC, undefined) || Object.is(testC, null)){
  console.log("The value is either undefined or null");
}

if (!(Object.is(testC, undefined) || Object.is(testC, null))){
  console.log("The value is neither undefined nor null");
}
Output:
true
false
The value is either undefined or null

看看他们:https://onecompiler.com/javascript/3ymdqd34v

Mozilla解释:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is

试试看:

if (!variable && typeof variable === "object") {
    // variable is null
}

我做了一个非常简单的功能,效果很好:

function safeOrZero(route) {
  try {
    Function(`return (${route})`)();
  } catch (error) {
    return 0;
  }
  return Function(`return (${route})`)();
}

路线是任何一条价值链都会爆炸。我将它用于jQuery/cacherio和对象等。

示例1:一个简单的对象,例如this const testObj={items:[{val:'haya'},{val:null},{val:'hum!'}];};。

但它可能是一个非常大的物体,我们甚至没有制造过。所以我通过了:

let value1 = testobj.items[2].val;  // "hum!"
let value2 = testobj.items[3].val;  // Uncaught TypeError: Cannot read property 'val' of undefined

let svalue1 = safeOrZero(`testobj.items[2].val`)  // "hum!"
let svalue2 = safeOrZero(`testobj.items[3].val`)  // 0

当然,如果您愿意,可以使用null或“无值”。。。任何适合您需要的。

通常,如果找不到DOM查询或jQuery选择器,可能会抛出错误。但使用类似于:

const bookLink = safeOrZero($('span.guidebook > a')[0].href);
if(bookLink){
  [...]
}