如何在字符串数组中引用字符串?

Ste*_*ven 5 javascript arrays

我有以下内容:

var tags = ["Favorite", "Starred", "High Rated"];

for (var tag in tags) {
    console.log(tag);
}
Run Code Online (Sandbox Code Playgroud)

输出是

0
1
2
Run Code Online (Sandbox Code Playgroud)

我想输出:

Favorite
Starred
High Rated
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?谢谢.

acd*_*ior 6

Itearting一个数组:

这是一个字符串数组,不要使用for..in,使用vanilla for循环:

var tags = ["Favorite", "Starred", "High Rated"];
for (var i = 0; i < tags.length; i++) { // proper way to iterate an array
    console.log(tags[i]);
}
Run Code Online (Sandbox Code Playgroud)

输出:

Favorite
Starred
High Rated
Run Code Online (Sandbox Code Playgroud)

正确使用for..in:

它适用于对象的属性,例如:

var tags2 = {"Favorite": "some", "Starred": "stuff", "High Rated": "here"};
for (var tag in tags2) { // enumerating objects properties
    console.log("My property: " + tag +"'s value is " +tags2[tag]);
}
Run Code Online (Sandbox Code Playgroud)

输出:

My property: Favorite's value is some
My property: Starred's value is stuff
My property: High Rated's value is here
Run Code Online (Sandbox Code Playgroud)

for..in数组的副作用:

不要相信我的话,让我们看看为什么不使用它:for..in在数组中可能有副作用.看一看:

var tags3 = ["Favorite", "Starred", "High Rated"];
tags3.gotcha = 'GOTCHA!'; // not an item of the array

// they can be set globally too, affecting all arrays without you noticing:
Array.prototype.otherGotcha = "GLOBAL!";

for (var tag in tags3) {
    console.log("Side effect: "+ tags3[tag]);
}
Run Code Online (Sandbox Code Playgroud)

输出:

Side effect: Favorite
Side effect: Starred
Side effect: High
Side effect: GOTCHA!
Side effect: GLOBAL!
Run Code Online (Sandbox Code Playgroud)

查看这些代码的演示小提琴.