It's easy to loop through the keys of a JavaScript associative array (hash):
var words = {
'a': 'apple',
'b': 'boy',
'c': 'car',
'd': 'dog'
}
for(var key in words) {
if(words.hasOwnProperty(key)) {
alert(words[key]);
}
}
The hasOwnProperty() method makes sure that your key does not exist as a result of inheritance (i.e. via the object's prototype).
If you have any code that extends the base Object's prototype:
Object.prototype.myFunction = function() {
};
var words = {
'a': 'apple',
'b': 'boy',
'c': 'car',
'd': 'dog'
}
for(var key in words) {
alert(words[key]);
}
then you will be looping over functions, etc. that exist in the base Object's prototype.
This will be alerted:
when that's probably not what you want.
Leave a comment