如何在JavaScript中检查空值?

时间:2011-05-14 18:15:35

标签: javascript null compare

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

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

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

}   

我怎样才能在JavaScript程序中找到错误?

20 个答案:

答案 0 :(得分:634)

Javascript在检查“null”值方面非常灵活。我猜你实际上在寻找空字符串,在这种情况下,这个更简单的代码将起作用:

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

将检查空字符串(""),nullundefinedfalse以及数字0NaN

请注意,如果您专门检查号码,使用此方法错过0是一个常见错误,并且首选num !== 0(或num !== -1~num (hacky代码也会检查-1))返回-1的函数,例如indexOf

答案 1 :(得分:316)

要检查空特定,您可以使用:

if(variable === null && typeof variable === "object")

......或者更简单:

if(variable === null)

此测试将传递给null,不会传递给""undefinedfalse0,或NaN

其余部分是对inorganik的评论的回应,是的,您可以单独检查每个评论。

您需要使用absolutely equals: ===typeof来完全确定您的支票。

I've created a JSFiddle here to show all of the individual tests working

以下是测试的所有输出:

Null Test:

if(variable === null && typeof variable === "object")

- 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 === "" && typeof variable === "string")

- 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(variable === undefined && typeof 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 && typeof variable === "boolean")

- 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 && typeof variable === "number")

- 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(!parseFloat(variable) && variable != 0 && typeof variable === "number")

- 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进行测试有点困难;

答案 2 :(得分:57)

只需在所有地方将==替换为===

==是一个松散或抽象的平等比较

===是严格的平等比较

有关详细信息,请参阅有关Equality comparisons and sameness的MDN文章。

答案 3 :(得分:25)

严格的相等运算符: -

我们可以===

检查null
if ( value === null ){

}

只需使用if

即可
if( value ) {

}
如果值不是

将评估为真:

  • 未定义
  • 的NaN
  • 空字符串(“”)
  • false
  • 0

答案 4 :(得分:11)

您可以按照以下步骤检查某些值是否为空

[pass,cpass,email,cemail,user].some(x=> x===null) 

let pass=1;
let cpass=2;
let email=3;
let cemail=null;
let user=5;

if ( [pass,cpass,email,cemail,user].some(x=> x===null) ) {     
    alert("fill all columns");
    //return false;  
}   

奖金:为什么=====source)更清楚

a == b

Enter image description here

a === b

Enter image description here

答案 5 :(得分:6)

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

更清洁的方式来检查就是简单地使用!操作者:

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

    alert("fill all columns");

}

答案 6 :(得分:5)

通过明确检查null但使用简化语法来改进已接受的答案:

if ([pass, cpass, email, cemail, user].every(x=>x!==null)) {
    // your code here ...
}

// Test
let pass=1, cpass=1, email=1, cemail=1, user=1; // just to test

if ([pass, cpass, email, cemail, user].every(x=>x!==null)) {
    // your code here ...
    console.log ("Yayy! None of them are null");
} else {
    console.log ("Oops! At-lease one of them is null");
}

答案 7 :(得分:4)

乍一看,这看起来像是覆盖率和严格性之间的简单权衡。

  • == 涵盖多个值,可以用更少的代码处理更多场景。
  • === 是最严格的,这使得它可以预测。

可预测性总是胜出,而这似乎使 === 成为一种万能解决方案。

enter image description here

但这是错误的。尽管 === 是可预测的,但它并不总是产生可预测的代码,因为它忽略了场景。

const options = { };
if (options.callback !== null) {
  options.callback();      // error --> callback is undefined.
}

一般来说 == 为空检查做了更可预测的工作:

  • 一般来说,nullundefined 都表示同一个意思:“缺少某些东西”。为了可预测性,您需要检查这两个值。然后 == null 做得很好,因为它恰好涵盖了这两个值。 (== null 等价于 === null && === undefined

  • 在特殊情况下,您确实希望在 nullundefined 之间有一个明确的区别。在这些情况下,最好使用严格的 === undefined=== null(例如,missing/ignore/skip 和 empty/clear/remove 之间的区别。)但它罕见

这不仅是罕见的,而且是需要避免的。您不能将 undefined 存储在传统数据库中。由于互操作性原因,您也不应该在 API 设计中依赖 undefined 值。但即使你根本不区分,你也不能假设undefined不会发生。我们周围的人间接地采取了概括null的行动/undefined这就是为什么像 this 这样的问题被关闭为“有意见的”。)。

那么,回到你的问题。使用 == null 没有任何问题。它做的正是它应该做的。

// FIX 1 --> yes === is very explicit
const options = { };
if (options.callback !== null && 
    options.callback !== undefined) {
  options.callback();
}


// FIX 2 --> but == covers both
const options = { };
if (options.callback != null) {
  options.callback();
}

答案 8 :(得分:4)

要在javascript中检查未定义 null ,您只需编写以下内容:

if (!var) {
        console.log("var IS null or undefined");
} else {
        console.log("var is NOT null or undefined");
}

答案 9 :(得分:4)

你可以使用try catch finally

 try {
     document.getElementById("mydiv").innerHTML = 'Success' //assuming "mydiv" is undefined
 } catch (e) {

     if (e.name.toString() == "TypeError") //evals to true in this case
     //do something

 } finally {}   

您还可以throw自己的错误。请参阅this

答案 10 :(得分:3)

在JavaScript中,没有字符串等于null

pass == null为空字符串时,您可能希望pass为真,因为您已经意识到松散等式运算符==执行某种类型的强制。

例如,这个表达式为真:

'' == 0

相反,严格相等运算符===表示这是错误的:

'' === 0

鉴于''0松散相等,您可能会合理地推测''null松散相等。但是,他们不是。

此表达式为false:

'' == null

将任何字符串与null进行比较的结果均为false。因此,pass == null和所有其他测试始终为false,用户永远不会收到警报。

要修复代码,请将每个值与空字符串进行比较:

pass === ''

如果您确定pass是一个字符串,pass == ''也会起作用,因为只有一个空字符串与空字符串松散相等。另一方面,一些专家说,在JavaScript中始终使用严格相等是一个好习惯,除非你特别想要做松散相等运算符所执行的类型强制。

如果您想知道哪些值对松散相等,请参阅表格"相同比较"在Mozilla article on this topic

答案 11 :(得分:3)

这是对WebWanderer关于检查NaN的解决方案的评论(我还没有足够的代表留下正式评论)。解决方案为

if(!parseInt(variable) && variable != 0 && typeof variable === "number")

但是对于有理数的数字会失败,这些数字会转到0,例如variable = 0.1。更好的测试是:

if(isNaN(variable) && typeof variable === "number")

答案 12 :(得分:1)

实际上,我认为您可能需要使用 if (value !== null || value !== undefined) 因为如果您使用if (value),则可能还会过滤0或错误值。

请考虑以下两个功能:

const firstTest = value => {
    if (value) {
        console.log('passed');
    } else {
        console.log('failed');
    }
}
const secondTest = value => {
    if (value !== null && value !== undefined) {
        console.log('passed');
    } else {
        console.log('failed');
    }
}

firstTest(0);            // result: failed
secondTest(0);           // result: passed

firstTest(false);        // result: failed
secondTest(false);       // result: passed

firstTest('');           // result: failed
secondTest('');          // result: passed

firstTest(null);         // result: failed
secondTest(null);        // result: failed

firstTest(undefined);    // result: failed
secondTest(undefined);   // result: failed

在我的情况下,我只需要检查该值是否为空且未定义,并且我不想过滤0false''值。因此我使用了第二个测试,但是您可能也需要过滤它们,这可能会导致您使用第一个测试。

答案 13 :(得分:1)

我找到了另一种方法来测试该值是否为空:

if(variable >= 0 && typeof variable === "object")

null同时充当numberobject。比较null >= 0null <= 0会得到true。比较null === 0null > 0null < 0将导致错误。但是由于null也是一个对象,我们可以将其检测为null。

我做了一个更复杂的功能 natureof ,女巫的表现要比typeof好,并且可以被告知要包括或保持分组的类型

/* function natureof(variable, [included types])
included types are 
    null - null will result in "undefined" or if included, will result in "null"
    NaN - NaN will result in "undefined" or if included, will result in "NaN"
    -infinity - will separate negative -Inifity from "Infinity"
    number - will split number into "int" or "double"
    array - will separate "array" from "object"
    empty - empty "string" will result in "empty" or
    empty=undefined - empty "string" will result in "undefined"
*/
function natureof(v, ...types){
/*null*/            if(v === null) return types.includes('null') ? "null" : "undefined";
/*NaN*/             if(typeof v == "number") return (isNaN(v)) ? types.includes('NaN') ? "NaN" : "undefined" : 
/*-infinity*/       (v+1 === v) ? (types.includes('-infinity') && v === Number.NEGATIVE_INFINITY) ? "-infinity" : "infinity" : 
/*number*/          (types.includes('number')) ? (Number.isInteger(v)) ? "int" : "double" : "number";
/*array*/           if(typeof v == "object") return (types.includes('array') && Array.isArray(v)) ? "array" : "object";
/*empty*/           if(typeof v == "string") return (v == "") ? types.includes('empty') ? "empty" : 
/*empty=undefined*/ types.includes('empty=undefined') ? "undefined" : "string" : "string";
                    else return typeof v
}

// DEMO
let types = [null, "", "string", undefined, NaN, Infinity, -Infinity, false, "false", true, "true", 0, 1, -1, 0.1, "test", {var:1}, [1,2], {0: 1, 1: 2, length: 2}]

for(i in types){
console.log("natureof ", types[i], " = ", natureof(types[i], "null", "NaN", "-infinity", "number", "array", "empty=undefined")) 
}

答案 14 :(得分:0)

请在downvote之前仔细查看。

JAVASCRIPT 中的AFAIK当变量声明但未指定值时,其类型为undefined。所以我们可以检查变量,即使它是object持有一些实例代替

创建一个辅助方法来检查返回true的nullity并在API中使用它。

帮助函数来检查变量是否为空:

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

try-catch异常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));

答案 15 :(得分:0)

如果来自DB的布尔值,这将不起作用 例如:

 value = false

 if(!value) {
   // it will change all false values to not available
   return "not available"
 }

答案 16 :(得分:0)

我做了一个非常简单的功能,可以实现奇迹:

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

路线是任何可能爆炸的价值链。我将它用于jQuery / cheerio和对象等。

示例1:一个简单的对象,例如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'No value' ...满足您需要的任何东西。

通常,如果未找到DOM查询或jQuery选择器,则可能会引发错误。但是使用类似的东西:

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

答案 17 :(得分:0)

检查错误情况:

// Typical API response data
let data = {
  status: true,
  user: [],
  total: 0,
  activity: {sports: 1}
}

// A flag that checks whether all conditions were met or not
var passed = true;

// Boolean check
if (data['status'] === undefined || data['status'] == false){
  console.log("Undefined / no `status` data");
  passed = false;
}

// Array/dict check
if (data['user'] === undefined || !data['user'].length){
  console.log("Undefined / no `user` data");
  passed = false;
}

// Checking a key in a dictionary
if (data['activity'] === undefined || data['activity']['time'] === undefined){
   console.log("Undefined / no `time` data");
   passed = false;
}

// Other values check
if (data['total'] === undefined || !data['total']){
  console.log("Undefined / no `total` data");
  passed = false;
}

// Passed all tests?
if (passed){
  console.log("Passed all tests");
}

答案 18 :(得分:-1)

试试这个:

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

答案 19 :(得分:-1)

您可以使用lodash模块检查值是否为空或未定义

_.isNil(value)
Example 

 country= "Abc"
    _.isNil(country)
    //false

   state= null
    _.isNil(state)
    //true

city= undefined
    _.isNil(state)
    //true

   pin= true
    _.isNil(pin)
    // false   

参考链接:https://lodash.com/docs/#isNil