1

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?

4

2 回答 2

1

最好使用数字遍历数组:

var i = 0;
for(i=0;i<names.length;i++){
 ...
}

您链接到的文章已经提到,任何其他对象属性,包括 Array.prototype 或 Object.prototype 上的东西都会出现在for ... in另一个不使用它的原因是 for .. in for Array 的速度较慢。

那篇文章确实提到了一个边缘情况,for ... in当数组的长度很大但只设置了几个项目时可能会更快。在这种情况下,我想您可以使用for ... inhasOwnProperty检查属性是否为数字:

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]);
    }
}
于 2013-07-17T00:27:25.113 回答
0

它比仅使用for loop.

86% slower在我的浏览器中(Google Chrome 28.0.1500.72)。

看看我做的这个基准。
虽然for..in循环只运行在110,772 ops/sec(仍然很快),for循环运行在791,792 ops/sec

我通常使用for..in带有objects. 我相信这就是他们真正的目的。

于 2013-07-17T00:27:50.357 回答