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?
最好使用数字遍历数组:
var i = 0;
for(i=0;i<names.length;i++){
...
}
您链接到的文章已经提到,任何其他对象属性,包括 Array.prototype 或 Object.prototype 上的东西都会出现在for ... in
另一个不使用它的原因是 for .. in for Array 的速度较慢。
那篇文章确实提到了一个边缘情况,for ... in
当数组的长度很大但只设置了几个项目时可能会更快。在这种情况下,我想您可以使用for ... in
并hasOwnProperty
检查属性是否为数字:
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]);
}
}
它比仅使用for loop
.
86% slower
在我的浏览器中(Google Chrome 28.0.1500.72)。
看看我做的这个基准。
虽然for..in
循环只运行在110,772 ops/sec
(仍然很快),for
循环运行在791,792 ops/sec
我通常使用for..in
带有objects
. 我相信这就是他们真正的目的。