我有以下内容:
var tags = ["Favorite", "Starred", "High Rated"];
for (var tag in tags) {
console.log(tag);
}
输出
0
1
2
我希望输出:
Favorite
Starred
High Rated
我该怎么做?感谢。
答案 0 :(得分:6)
这是一个字符串数组,不要使用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!
答案 1 :(得分:0)
在JavaScript中的in
循环中使用for
与Java中的:
或其他语言中的foreach不同 - 它不提供对元素的引用,而是提供其索引。
如果你使用像jQuery这样的框架,那么有一个方法 - $.each
可以在迭代时通过回调访问元素(不仅仅是索引):
var a = ["Favorite", "Starred", "High Rated"];
$.each ( a, function ( index, data )
{
console.log ( data );
});