Just wonder. I have extended javascript Array object using its prototype as follows:
for..in
iterates over the (non built-in) properties of an object. Do not use it to iterate through an array. Just use a regular for
loop.
Read this link https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for...in#Description
A question would be helpful ;-)
I assume you don't want the prototype property to show up? JS doesn't allow you to set "DontEnum" on properties you add to the prototype, so you have to check to see if the array has the property, or if it's a property of its prototype:
for(var i in ax) {
if (a.hasOwnProperty(i)) {
document.write(ax[i]);
}
}
although to iterate over an array you shouldn't really be using for...in
as that's for iterating over the properties of an object, rather than the elements of an array.
Crockford does a great job of explaining this on his site and in his videos. It sounds like you are abusing the Array type by using it as a hash table. In which case you will need to do the following
From Crockford:
JavaScript has very nice notational conveniences for manipulating hashtables.
var myHashtable = {};
This statement makes a new hashtable and assigns it to a new local variable. JavaScript is loosely typed, so we don't use type names in declarations. We use subscript notation to add, replace, or retrieve elements in the hashtable.
myHashtable["name"] = "Carl Hollywood";
There is also a dot notation which is a little more convenient.
myHashtable.city = "Anytown";
The dot notation can be used when the subscript is a string constant in the form of a legal identifier. Because of an error in the language definition, reserved words cannot be used in the dot notation, but they can be used in the subscript notation.
You can see that JavaScript's hashtable notation is very similar to Java's object and array notations. JavaScript takes this much farther: objects and hashtables are the same thing, so I could have written
var myHashtable = new Object();
and the result would have been exactly the same.
There is an enumeration capability built into the for statement.
for (var n in myHashtable) { if (myHashtable.hasOwnProperty(n)) { document.writeln("<p>" + n + ": " + myHashtable[n] + "</p>"); } }
I beleive the jquery .each code does this for you but I'm not 100% sure.
If you are using an actual Array and want to use it properly, you should just do
for (var i = 0; i < myArray.length; i++)
{
alert(myArray[i]);
}