简体   繁体   中英

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.

But the problem is here that "" or null == 0 is true,

So please help me to get out this problem, Thanks in Advance

Use === for comparisons in 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. 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.

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.

line 1: var a = 0; line 2: a = (a!==0 && !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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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