I have an array variable like Array[0], and now I need to check whether that Array[0] contains value or not inside of it. What should I do?
-
Possible duplicate of stackoverflow.com/q/610842/544184Karlisson– Karlisson2012-01-11 11:55:07 +00:00Commented Jan 11, 2012 at 11:55
-
And what's your definition of whether or not the variable "contains value"?Lightness Races in Orbit– Lightness Races in Orbit2012-01-11 12:00:30 +00:00Commented Jan 11, 2012 at 12:00
Add a comment
|
4 Answers
If you have an array and call it eg. list, then you can check if it has some elements in the following manner:
if (list.length){
// has some elements (exactly list.length elements)
} else {
// does not have any elements
}
See the following for details: Documentation on length property of Array objects in JavaScript
Comments
//pass array variable to this function
function isEmpty(array){
if(array.length == 0)
return true;
else
return false;
}
3 Comments
Jørgen
Why would you want the added complexity and overhead using a function for this?
Mick Hansen
Question asks to check if first index is empty, not if the array is empty.
Checks if that array exists and does something if not so.
if(!array[0])
{
//do something
}
6 Comments
Manticore
However you need it, but thanks for the correction :) I'm always open to good tips.
Tadeck
@Karlisson: You say
false, 0 etc. are not "values"? OP asked: "I need to check whether that Array[0] contains value or not inside of it".Tadeck
@Karlisson: The original was "need to check weather that array[0] containing value or not inside of if...", so I would not expect it to stay unedited ;) But it is matter of interpretation in that case, I suppose ;)
Brian
The code would generally work but if(foo[0] !== undefined){} is more accurate, as your code would fail if it had a false value.
Tadeck
@manticore: It depends.
undefined sometimes can be overwritten with something else (although can be restored by simple trick). You can also use typeof foo[0] !== 'undefined', I believe. Please search on StackOverflow for other tipses on how to deal with undefined being actually defined (such as when you invoke (function(undefined){/* your code here */}());, the undefined variable within the anonymous function is actually undefined, as you do not pass it within call / brackets calling the function). |