我想使用多个字符串来做同样的事情。我想这样做:
names = ["NOTE", "REPLICA", "HINT", "VIEW"];
for (name in names) {
name = names[name];
//do stuff
}
然后我读到 this 。还可以吗?
最佳答案
最好使用数字来遍历数组:
var i = 0;
for(i=0;i<names.length;i++){
...
}
您链接到的文章已经提到,任何其他对象属性(包括 Array.prototype 或 Object.prototype 上的内容)都会显示在 for ... in
中,不使用它的另一个原因是 for .. 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]);
}
}
关于javascript - for .. in 的这种用法可以接受吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17689126/