How do I reference the string in a array of strings?
本问题已经有最佳答案,请猛点这里访问。
我有以下几点:
1 2 3 4 5 | var tags = ["Favorite","Starred","High Rated"]; for (var tag in tags) { console.log(tag); } |
输出是
1 2 3 | 0 1 2 |
我想输出:
1 2 3 | Favorite Starred High Rated |
我该怎么做?谢谢。
在数组上启动:
这是一个字符串数组,不要使用
1 2 3 4 | var tags = ["Favorite","Starred","High Rated"]; for (var i = 0; i < tags.length; i++) { // proper way to iterate an array console.log(tags[i]); } |
输出:
1 2 3 | Favorite Starred High Rated |
正确使用
它用于对象的属性,例如:
1 2 3 4 | 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]); } |
输出:
1 2 3 | My property: Favorite's value is some My property: Starred's value is stuff My property: High Rated's value is here |
带阵列的
不要相信我的话,让我们看看为什么不使用它:数组中的
1 2 3 4 5 6 7 8 9 | 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]); } |
输出:
1 2 3 4 5 | Side effect: Favorite Side effect: Starred Side effect: High Side effect: GOTCHA! Side effect: GLOBAL! |
看到这些代码的演示小提琴。
在EDCOX1中使用EDOCX1 5,在JavaScript中的1个循环不像Java中的EDCOX1,7或其他语言中的前缀,而不是提供对元素的引用,而是提供它的索引。如果您使用类似jquery的框架,那么有一个方法-
1 2 3 4 5 | var a = ["Favorite","Starred","High Rated"]; $.each ( a, function ( index, data ) { console.log ( data ); }); |