如何在 JavaScript 中检查空值?

发布于 2024-11-07 17:56:39 字数 241 浏览 0 评论 0原文

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

if (pass == null || cpass == null || email == null || cemail == null || user == null) {
  alert("fill all columns");
  return false;
}

How can I check for null values in JavaScript? I wrote the code below but it didn't work.

if (pass == null || cpass == null || email == null || cemail == null || user == null) {
  alert("fill all columns");
  return false;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(24

莫相离 2024-11-14 17:56:39

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

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

它将检查空字符串 (""), null, <代码>未定义,<代码>假和数字<代码>0和<代码>NaN。

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

JavaScript is very flexible with regards to checking for "null" values. I'm guessing you're actually looking for empty strings, in which case this simpler code will work:

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

Which will check for empty strings (""), null, undefined, false and the numbers 0 and NaN.

Please note that if you are specifically checking for numbers, it is a common mistake to miss 0 with this method, and num !== 0 is preferred (or num !== -1 or ~num (hacky code that also checks against -1)) for functions that return -1, e.g. indexOf).

说谎友 2024-11-14 17:56:39

专门检查 null,您可以使用:

if (variable === null)

此测试将ONLY通过 null,而不会通过 ""、未定义false0NaN

此外,我还为每个“类似 false”的值(对于 !variable 返回 true 的值)提供了绝对检查。

请注意,对于某些绝对检查,您需要实现使用 absolute equals: ===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 进行测试有点困难;

To check for null SPECIFICALLY you would use this:

if (variable === null)

This test will ONLY pass for null and will not pass for "", undefined, false, 0, or NaN.

Additionally, I've provided absolute checks for each "false-like" value (one that would return true for !variable).

Note, for some of the absolute checks, you will need to implement use of the absolutely equals: === and typeof.

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

Here is the output of each check:

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

As you can see, it's a little more difficult to test against NaN;

冰之心 2024-11-14 17:56:39

只需将所有位置的 == 替换为 === 即可。

== 是松散或抽象的相等比较

=== 是严格的相等比较

请参阅 MDN 文章 相等性比较和相同性了解更多详细信息。

just replace the == with === in all places.

== is a loose or abstract equality comparison

=== is a strict equality comparison

See the MDN article on Equality comparisons and sameness for more detail.

回忆追雨的时光 2024-11-14 17:56:39

您可以检查某个值是否为空,如下所示

[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;  
}   

额外奖励:为什么 ===== 更清晰(来源)

a == b

在此处输入图像描述

a === b

在此处输入图像描述

You can check if some value is null as follows

[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;  
}   

BONUS: Why === is more clear than == (source)

a == b

Enter image description here

a === b

Enter image description here

怪我闹别瞎闹 2024-11-14 17:56:39

严格相等运算符:-

我们可以通过===检查null,

if ( value === null ){

}

只要使用if

if( value ) {

}

,如果值不<,则计算结果为true /strong>:

  • null
  • 未定义
  • NaN
  • 空字符串 ("")
  • false
  • 0

Strict equality operator:-

We can check null by ===

if ( value === null ){

}

Just by using if

if( value ) {

}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • false
  • 0
如若梦似彩虹 2024-11-14 17:56:39

乍一看,它看起来像是覆盖范围和严格性之间的简单权衡

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

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

输入图像描述这里

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

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

一般 == 对 null 检查的工作更可预测:

  • 一般来说,nullundefined两者的意思是相同的:“缺少某些东西”。为了可预测性,您需要检查这两个值。然后 == null 就完成了完美的工作,因为它完全涵盖了这两个值。 (== null 相当于 === null && === undefined

  • 在特殊情况下,您 < strong>确实希望在nullundefined之间有明确的区别。在这些情况下,您最好使用严格的 === undefined=== null(例如,缺失/忽略/跳过和空/清除/删除之间的区别。)但这种情况罕见

这不仅罕见,而且是应该避免的。您无法在传统数据库中存储undefined。由于互操作性原因,您也不应该在 API 设计中依赖 undefined 值。但即使你根本不做区分,你也不能假设未定义不会发生。我们周围的人都会间接采取概括的行动>null/undefined这就是为什么像 被关闭为“固执己见”。)。

那么,回到你的问题。使用 == 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();
}

// FIX 3 --> optional chaining also covers both.
const options = { };
options.callback?.();

At first sight, it looks like a simple trade-off between coverage and strictness.

  • == covers multiple values, can handle more scenarios in less code.
  • === is the most strict, and that makes it predictable.

Predictability always wins, and that appears to make === a one-fits-all solution.

enter image description here

But it is wrong. Even though === is predictable, it does not always result in predictable code, because it overlooks scenarios.

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

In general == does a more predictable job for null checks:

  • In general, null and undefined both mean the same thing: "something's missing". For predictability, you need to check both values. And then == null does a perfect job, because it covers exactly those 2 values. (i.e. == null is equivalent to === null && === undefined)

  • In exceptional cases you do want a clear distinction between null and undefined. And in those cases you're better of with a strict === undefined or === null. (e.g. a distinction between missing/ignore/skip and empty/clear/remove.) But it is rare.

It is not only rare, it's something to avoid. You can't store undefined in a traditional database. And you shouldn't rely on undefined values in your API designs neither, due to interopability reasons. But even when you don't make a distinction at all, you can't assume that undefined won't happen. People all around us indirectly take actions that generalize null/undefined (which is why questions like this are closed as "opinionated".).

So, to get back to your question. There's nothing wrong with using == null. It does exactly what it should do.

// 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();
}

// FIX 3 --> optional chaining also covers both.
const options = { };
options.callback?.();
夏の忆 2024-11-14 17:56:39

通过显式检查 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");
}

Improvement over the accepted answer by explicitly checking for null but with a simplified syntax:

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");
}

彩扇题诗 2024-11-14 17:56:39

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

进行检查的一种更简洁的方法是简单地使用 !操作员:

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

    alert("fill all columns");

}

Firstly, you have a return statement without a function body. Chances are that that will throw an error.

A cleaner way to do your check would be to simply use the ! operator:

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

    alert("fill all columns");

}
忱杏 2024-11-14 17:56:39

你可以使用 try catch 最后,

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

你也可以抛出你自己的错误。请参阅

you can use 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 {}   

you can also throw your own errors. See this.

我ぃ本無心為│何有愛 2024-11-14 17:56:39

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

也许您希望当 pass 为空字符串时 pass == null 为 true,因为您知道松散相等运算符 == 执行某些类型的类型强制。

例如,此表达式为 true:

'' == 0

相反,严格相等运算符 === 表示这是 false:

'' === 0

鉴于 ''0 > 是松散相等的,您可能会合理地推测 ''null 是松散相等的。然而,事实并非如此。

此表达式为 false:

'' == null

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

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

pass === ''

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

如果您想知道哪些值对松散相等,请参阅 关于此主题的 Mozilla 文章

In JavaScript, no string is equal to null.

Maybe you expected pass == null to be true when pass is an empty string because you're aware that the loose equality operator == performs certain kinds of type coercion.

For example, this expression is true:

'' == 0

In contrast, the strict equality operator === says that this is false:

'' === 0

Given that '' and 0 are loosely equal, you might reasonably conjecture that '' and null are loosely equal. However, they are not.

This expression is false:

'' == null

The result of comparing any string to null is false. Therefore, pass == null and all your other tests are always false, and the user never gets the alert.

To fix your code, compare each value to the empty string:

pass === ''

If you're certain that pass is a string, pass == '' will also work because only an empty string is loosely equal to the empty string. On the other hand, some experts say that it's a good practice to always use strict equality in JavaScript unless you specifically want to do the type coercion that the loose equality operator performs.

If you want to know what pairs of values are loosely equal, see the table "Sameness comparisons" in the Mozilla article on this topic.

孤独患者 2024-11-14 17:56:39

要检查 JavaScript 中的 undefinednull,您只需编写以下内容:

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

to check for undefined and null in javascript you need just to write the following :

if (!var) {
        console.log("var IS null or undefined");
} else {
        console.log("var is NOT null or undefined");
}
ゃ人海孤独症 2024-11-14 17:56:39

实际上我认为你可能需要使用
if(值!== null &&值!==未定义)
因为如果您使用 if (value) 您也可能会过滤 0 或 false 值。

考虑这两个函数:

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

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

Actually I think you may need to use
if (value !== null && value !== undefined)
because if you use if (value) you may also filter 0 or false values.

Consider these two functions:

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

In my situation, I just needed to check if the value is null and undefined and I did not want to filter 0 or false or '' values. so I used the second test, but you may need to filter them too which may cause you to use first test.

梦中的蝴蝶 2024-11-14 17:56:39

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

检查空值

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:
This is a Null Value
let x = null;
if (x === null) {
  console.log("x is null");
}
Output:
x is null

检查未定义值(已声明变量,但尚未赋值。)

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:
This is an undefined Value

如果对象尚未声明,则不能使用。作为替代方案,您可以尝试以下操作:

if (typeof x === "undefined") {
  console.log("x is undefined");
}
Output:
The value is either undefined or null

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

The 'Object.is()' method can be used to determine if two values are the same value. So, you can use it to check whether the object is null or not.

Check for null values

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:
This is a Null Value
let x = null;
if (x === null) {
  console.log("x is null");
}
Output:
x is null

Check for undefined values (A variable has been declared, but a value has not been assigned.)

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:
This is an undefined Value

If the object has not been declared, this cannot be used. As an alternative, you may try this:

if (typeof x === "undefined") {
  console.log("x is undefined");
}
Output:
The value is either undefined or null

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

抽个烟儿 2024-11-14 17:56:39

这是对 WebWanderer 关于检查 NaN 的解决方案的评论(我还没有足够的代表来发表正式评论)。解决方案如下所示,

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

但对于有理数会失败,因为有理数会四舍五入到 0,例如 variable = 0.1。更好的测试是:

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

This is a comment on WebWanderer's solution regarding checking for NaN (I don't have enough rep yet to leave a formal comment). The solution reads as

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

but this will fail for rational numbers which would round to 0, such as variable = 0.1. A better test would be:

if(isNaN(variable) && typeof variable === "number")
半透明的墙 2024-11-14 17:56:39

您可以使用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

You can use lodash module to check value is null or undefined

_.isNil(value)
Example 

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

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

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

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

Reference link: https://lodash.com/docs/#isNil

兮子 2024-11-14 17:56:39

据我所知,在JAVASCRIPT中,当声明变量但尚未赋值时,其类型为未定义。因此我们可以检查变量,即使它是一个持有某些实例代替对象

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

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

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));

AFAIK in JAVASCRIPT when a variable is declared but has not assigned value, its type is undefined. so we can check variable even if it would be an object holding some instance in place of value.

create a helper method for checking nullity that returns true and use it in your API.

helper function to check if variable is empty:

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

try-catch exceptional API call:

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;
    }
}

some test cases:

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));
愿得七秒忆 2024-11-14 17:56:39

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

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

null 同时充当 numberobject。比较 null >= 0null <= 0 结果为 true。比较 null === 0null > 0null < 0 将导致 false。但由于 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")) 
}

I found a another way to test if the value is null:

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

null acts as a number and object at the same time. Comparing null >= 0 or null <= 0 results in true. Comparing null === 0 or null > 0 or null < 0 will result in false. But as null is also an object we can detect it as a null.

I made a more complex function natureof witch will do better than typeof and can be told what types to include or keep grouped

/* 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")) 
}

热血少△年 2024-11-14 17:56:39

我制作了这个非常简单的函数,它产生了奇迹:

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){
  [...]
}

I made this very simple function that works wonders:

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

The route is whatever chain of values that can blow up. I use it for jQuery/cheerio and objects and such.

Examples 1: a simple object such as this const testObj = {items: [{ val: 'haya' }, { val: null }, { val: 'hum!' }];};.

But it could be a very large object that we haven't even made. So I pass it through:

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

Of course if you prefer you can use null or 'No value'... Whatever suit your needs.

Usually a DOM query or a jQuery selector may throw an error if it's not found. But using something like:

const bookLink = safeOrZero($('span.guidebook > a')[0].href);
if(bookLink){
  [...]
}
一场信仰旅途 2024-11-14 17:56:39

空值的简单解决方案:

function isEmpty(value) {
        return (
            value === null || value === undefined || value === '' ||
            (Array.isArray(value) && value.length === 0) ||
            (!(value instanceof Date) && typeof value === 'object' && Object.keys(value).length === 0)
        );
    }

Simple Solution for empty values:

function isEmpty(value) {
        return (
            value === null || value === undefined || value === '' ||
            (Array.isArray(value) && value.length === 0) ||
            (!(value instanceof Date) && typeof value === 'object' && Object.keys(value).length === 0)
        );
    }
心房敞 2024-11-14 17:56:39

这是一个非常非人类的代码。但有效:

if((pass, cpass, email, cemail, user !== null)){

只要尝试一下即可帮助找到答案

This is a very non-human code. But works:

if((pass, cpass, email, cemail, user !== null)){

Just try it out and help the answer

南笙 2024-11-14 17:56:39

与操作员进行可选检查怎么样?

例如:

// check mother for null or undefined and 
// then if mother exist check her children also
// this 100% sure it support and valid in JS today.
// Apart of that C# have almost the same operator using the same way
if (mother?.children) {

}
else {
 // it is null, undefined, etc...

}

What about optional check with operator ?

for example:

// check mother for null or undefined and 
// then if mother exist check her children also
// this 100% sure it support and valid in JS today.
// Apart of that C# have almost the same operator using the same way
if (mother?.children) {

}
else {
 // it is null, undefined, etc...

}
风为裳 2024-11-14 17:56:39

试试这个:

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

Try this:

if (!variable && typeof variable === "object") {
    // variable is null
}
司马昭之心 2024-11-14 17:56:39

如果布尔值来自数据库,这将不起作用
例如:

 value = false

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

This will not work in case of Boolean values coming from DB
for ex:

 value = false

 if(!value) {
   // it will change all false values to not available
   return "not available"
 }
我做我的改变 2024-11-14 17:56:39

检查错误条件:

// 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");
}

Checking error conditions:

// 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");
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文