简体   繁体   English

区分0和“”

[英]differentiate between 0 & “”

I know, I know there must be some threads covering this topic. 我知道,我知道必须有一些线索涵盖这个主题。 But I used the search and didn't get the answer which fits my needs. 但我使用搜索并没有得到符合我需要的答案。 So here we go: 所以我们走了:

i want to check one "if" condition , in that if variable is having values like "null" or "undefined" or "" or '' then i want to assign variable value as "N/A" & if value is zero (0) it should not assign "N/A" to that variable. 我想检查一个“if”条件,因为如果变量具有类似“null”或“undefined”或“”或“'的值,那么我想将变量值指定为”N / A“并且如果值为零( 0)它不应该为该变量分配“N / A”。

But the problem is here that "" or null == 0 is true, 但问题是“”或null == 0是真的,

So please help me to get out this problem, Thanks in Advance 所以请帮我解决这个问题,先谢谢

Use === for comparisons in JavaScript , 使用===进行JavaScript比较,

// type doesn't match gives false
0 === null; // false
0 === undefined; // false
0 === ''; // false
0 === false; // false
0 === "0"; // false

// type matches
0 === 0; // true

Is this what you are talking about? 这是你在说什么? The "===" is a strict comparison operator that will not change data types. “===”是一个严格的比较运算符,不会更改数据类型。

if (val === undefined || val === null || val === ""){
    // do something
}else{
    // do something else
}

In Javascript, null, undefined, "" (empty string), false, 0, NaN are falsy values. 在Javascript中,null,undefined,“”(空字符串),false,0,NaN是虚假值。 Condition checking a variable having any of these values results in false. 检查具有任何这些值的变量的条件导致错误。

In your case you can simply check if variable is falsy or not and if you need to exclude 0 from this condition, you can add one more condition check for if variable !== 0. 在您的情况下,您可以简单地检查变量是否为假,如果您需要从此条件中排除0,则可以为if变量添加一个条件检查!== 0。

for example in the below code say 'a' is the variable you need to check against all falsy values except 0, then then you can check if (a!==0) && !a (not of falsy) and assign to N/A else leave 'a' as it is. 例如,在下面的代码中说'a'是你需要检查除0之外的所有虚假值的变量,然后你可以检查是否(a!== 0)&&!a(不是falsy)并分配给N /其他人留下'a'原样。

line 1: var a = 0; 第1行:var a = 0; line 2: a = (a!==0 && !a)? 第2行:a =(a!== 0 &&!a)? "N/A" : a; “N / A”:a;

I hope the above code may help you. 我希望上面的代码可以帮到你。

Is this what you are after? 这就是你追求的吗? Just a single test case should be sufficient... 只需一个测试用例就足够了......

if ($var !== 0) $var = 'N/A';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM