For some reason, when I try to loop through a JavaScript array that has only one item, I get an error that the array is undefined. If I add another item to the array, no problem.
This works:
var myArray = new Array(-1, 1);
This doesn’t:
var myArray = new Array(1);
Any idea why? Am I missing something basic here?
UPDATE: Here is sample looping code:
function loop(thisArray) {
for (i = 0; i < thisArray.length; i++) {
alert(thisArray[i]);
}
}
and a test file.
UPDATE #2: Dougal posts a solution in the comments.
This comment is not based on any knowledge of javascript, just a guess based on generic ‘typeless’ languages.
Is it possible that because the array is only size 1 the interpreter considers that to be a non-array typed variable, and thus not able to be used for array operations. When you add the second item it silently converts it to an array type?
I have seen this sort of behaviour before with languages so it could be.
A snippet of the code that you use to loop over the array might help…
Added it into the post.
The JS interpreter is using the usual syntax for creating an empty array of n elements, and creating a one-element empty array.
Try bracket syntax: myArr = [1]
Thanks Dougal, works like a charm!