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

时间:2013-07-06 02:11:36

标签: javascript arrays

我有以下内容:

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

for (var tag in tags) {
    console.log(tag);
}

输出

0
1
2

我希望输出:

Favorite
Starred
High Rated

我该怎么做?感谢。

2 个答案:

答案 0 :(得分:6)

Itearting over a array:

这是一个字符串数组,不要使用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]);
}

输出:

Favorite
Starred
High Rated

正确使用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]);
}

输出:

My property: Favorite's value is some
My property: Starred's value is stuff
My property: High Rated's value is here

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]);
}

输出:

Side effect: Favorite
Side effect: Starred
Side effect: High
Side effect: GOTCHA!
Side effect: GLOBAL!

<强> See a demo fiddle for these codes.

答案 1 :(得分:0)

在JavaScript中的in循环中使用for与Java中的:或其他语言中的foreach不同 - 它不提供对元素的引用,而是提供其索引。 如果你使用像jQuery这样的框架,那么有一个方法 - $.each可以在迭代时通过回调访问元素(不仅仅是索引):

var a = ["Favorite", "Starred", "High Rated"];
$.each ( a, function ( index, data ) 
{
   console.log ( data );
});