Reputation: 65510
In my JavaScript I currently have this nice expression:
var b = {
items: +a || null
};
This sets b.items
to a Number if a
is a String, or a Number greater than 0, and as null
if a
is null
/undefined
.
However, it also returns null
if a
is 0. Now I'd like to change it so that it returns 0 if a
is 0. (This seems like the right way to handle real data: if it's zero, we want to know that it's zero, and if it doesn't exist, we want to know that too.)
I've looked at this question and tried these two:
items: 1/a ? +a: null
items: isNaN(a) ? null : +a
but these both return 0 if a
is null. They should return null.
Is there a way I can return 0 if a
is 0, and null
if it's undefined?
Update: Here's a summary of everything the expression needs to do:
"72" -> 72
"0" -> 0
1 -> 1
0 -> 0
null -> null
undefined -> null
Upvotes: 2
Views: 827
Reputation: 1762
This should work as well:
var b = {
items: a != null? +a : null
};
Based on https://stackoverflow.com/a/15992131/1494833
Upvotes: 0
Reputation: 87203
You can check the type of a
in ternary operator.
var b = {
items: typeof (+a) == 'number' ? +a : null
};
Demo:
var b = {
items: typeof (+"0") == 'number' ? +"0" : null
};
alert(b.items);
EDIT
Hack to check null
.
function f(a) {
return isNaN('' + a) ? null : parseFloat(a)
}
alert(f(0));
alert(f(null));
alert(f(undefined));
Upvotes: 1
Reputation: 2628
You could specifically test for null and undefined
var b = {
items: ('undefined' === typeof a || null === a) ? null : +a
};
Upvotes: 1