I'd like to do the same thing using several strings. I'd like to do it like this:
names = ["NOTE", "REPLICA", "HINT", "VIEW"];
for (name in names) {
name = names[name];
//do stuff
}
Then I read this. Is it still OK?
I'd like to do the same thing using several strings. I'd like to do it like this:
names = ["NOTE", "REPLICA", "HINT", "VIEW"];
for (name in names) {
name = names[name];
//do stuff
}
Then I read this. Is it still OK?
It's better to go through an array using a number:
var i = 0;
for(i=0;i<names.length;i++){
...
}
the article you link to already mentioned that any other object properties including stuff on Array.prototype or Object.prototype will show up in for ... in
another reason not to use it is that for .. in for Array's is slower.
That article does mention an edge case where for ... in
could be faster when the lenght of the array is big but only a couple of items are set. In that case I guess you can use for ... in
with hasOwnProperty
and checking if the property is a number:
var stuff, index;
stuff = [];
stuff[0] = "zero";
stuff[9999] = "nine thousand nine hundred and ninety-nine";
stuff.name = "foo";
for (index in stuff)
{
if (stuff.hasOwnProperty(index) && String(Number(index)) === index) {
console.log("stuff[" + index + "] = " + stuff[index]);
}
}
It's a lot slower than just using a for loop
.
Around 86% slower
in my browser (Google Chrome 28.0.1500.72).
Check out this benchmark I made.
While for..in
loops only ran at 110,772 ops/sec
(still fast), for
loops ran at 791,792 ops/sec
I typically use for..in
loops with objects
. I believe that's what they are actually for.