How to make 0 return true?
I have a situation where I am searching for something in an array, and if a value is found, I do something. I am doing this by setting a variable to undefined, and then when the value is found, setting to the index of the element found. This would work if the value returned is anything but 0, but if it is 0, then it returns as false. How can I work aroun开发者_如何学编程d this?
var index = undefined;
for(var i=0; i<ARRAY; i++)
{
if(CONDITION)
index = i;
}
if(index)
{
DO SOMETHING
}
So my problem occurred when the index turned out to be zero, because this returned false. The reason I want to do it this way is because I am not sure if it exists in the array or not.
How about testing the result to see whether it's >= 0
instead of relying on its truthyness?
if (index >= 0) { ... }
The undefined
value is not >= 0
so that should work.
Why not be 100% explicit? This is, after all, what you're actually intending to check:
if (typeof index === 'number')
{
// DO SOMETHING
}
I prefer this even to checking >= 0
since that operator gives some weird results for non-numeric values:
Input | >= 0
------------
"1" | true
false | true
null | true
[] | true
"" | true
(See this jsFiddle for evidence.)
You mean you have a variable that may be undefined
or some number, and you want undefined
to be distinguishable from 0
?
Then:
if (index) // wrong
if (index >= 0) // right
Or you can use type-aware comparisons:
if (index !== undefined) { .. }
You can use -1 to indicate the index was not found in the array. As you mentioned, 0 will be implicitly cast to a "false" if you use it like a boolean. You can use === to avoid an implicit cast.
You could... not do it like that, because you need to work within JS's definition of truthiness, or check explicitly for undefined
.
0
is falsey in javascript; use ===
to test whether a value is actually false:
foo = 0;
foo == false //true
foo === false //false
As you're setting the value to undefined
one way of testing is to see whether the value is Not a Number:
if (!isNaN(foo))
{
//foo is numeric
}
I wrote these simple utility functions to help with more math-oriented tasks:
function isFalsy(val) {
return (((!val)&&(val!==0))||(val === null)||(val === NaN)||(val === ""))
}
function isTruthy(val) {
return !isFalsy(val)
}
精彩评论