简体   繁体   中英

How to get the variable that triggered the if function?

So, I'm working on a game, and I want it so that if any of the variables are "NaN" or undefined, variableThatTriggeredThis will be set to 0.

I didn't try anything so far, I have no ideas how I can fix it.

if(example == NaN || foo == NaN || bar == NaN) {
    variableThatTriggeredThis = 0;
}

I also wanted to ask if there's a way to select every variable in the code, or for example multiple variables, just like var(one, two) == "100".

You can check variables directly. NaN or undefined are valued as false.

Then use Logical OR ||

expr1 || expr2 expr1 || expr2 If expr1 can be converted to true, returns expr1 ; else, returns expr2

Example:

example = example || 0 ;
foo = foo || 0 ; 
bar = bar || 0 ; 

There are several ways you could write this. Here's one option using array destructuring:

 let a = 10; let b = 0/0; // NaN let c; // undefined const undefinedOrNaNCheck = value => (value === undefined || Number.isNaN(value))? 0: value; [a, b, c] = [a, b, c].map(undefinedOrNaNCheck); console.log([a, b, c]);

To test if a variable v is undefined (has undefined value) use: typeof(v) === "undefined"
To test if a variable v has NaN value use: Number.isNaN(v)

To coerce a variable into a number (defaulting to 0):

example = isNaN(example)? 0: example * 1;

To process several variables, one approach is to create a parent object:

const scores = {};
scores.example = 10;
scores.foo = undefined;
scores.bar = 'not a number';

... allowing iteration like this:


Object.keys(scores).forEach(function(key) {   
  scores[key] = isNaN(scores[key]) ? 0 : scores[key] * 1;
});

Here's a working fiddle .

If you're supporting an older version of javascript (eg. older browsers) you'll need to use "var" instead of "const" and use a "for" loop instead of the "forEach" loop shown above.

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