this seems to be a common javascript idiom:
function foo (array, index) {
if (typeof array[index] == \'undefined\')
alert (\'out of bounds baby\'
You can also write:
if (index in array) {
which will return true even if array[index]
is set to undefined
.
Do not test for undefined. You should use the length of the array. There are cases where it simply does not work to test for undefined because undefined is a legal value for legitimate array entry. Here's a legal JS array:
var legalArray = [4, undefined, "foo"];
And you can access it like this:
var legalArray = [4, undefined, "foo"];
var result = "";
for (var i = 0; i < legalArray.length; i++) {
result += legalArray[i] + "<br>";
}
$("#result").html(result);
Generates this output:
4
undefined
foo
As seen in this jsFiddle: http://jsfiddle.net/jfriend00/J5PPe/
It's not common as far as I know, much more common is:
for (var i=0, iLen=array.length; i<iLen; i++) {
// do stuff
}
You should not compare to undefined, since a member of the array may have been assigned a value of undefined
, or may not have been assigned any value.
e.g.
var a = [0,,,,];
alert(a.length); // 4 (or 5 in buggy IE);
a[1] === undefined; // true but not out of bounds
The main reason for using a for loop is that array properties may not be returned in numeric order if a for..in loop is used.
A for..in loop is much more efficient in sparse arrays but the possible out-of-order access must be dealt with if it matters (as must inherited and non-numeric enumerable properties if they should be avoided).
The only correct way is to check the index vs. the length.
An element may be assigned the value undefined
. It is just silly to use it for a sentinel here. (There may be other, valid and possibly overlapping, reasons for checking for undefined, but not "for an out of bound check" -- the code in the other question will present arguably wrong results when the value of the given arg is really undefined
.)
Happy coding.
In that case, the test it to make sure that it does not accidentally add the String "undefined" to the calling String. In the case below, it will actually do just that:
var undefd;
"{0} is dead, but {1} is alive! {0} {2}".format("ASP", undefd, "ASP.NET")
// output as "ASP is dead, but {1} is alive! ASP ASP.NET"
Personally, though, I would probably simply cache the length and then do a numeric comparison.
Side note: his method also avoids a NaN check but forces a strict parallel:
// this will fail unless 0001 is cast to a number, which means the method
// provided will fail.
"{0} is dead, but {1} is alive! {0001} {2}".format("ASP", "ASP.NET")