我如何引用字符串数组中的字符串? [英] How do I reference the string in a array of strings?
本文介绍了我如何引用字符串数组中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下内容:
var tags = ["Favorite", "Starred", "High Rated"];
for (var tag in tags) {
console.log(tag);
}
输出为
0
1
2
我想它想的输出:
I'd like it to output:
Favorite
Starred
High Rated
我如何做到这一点?谢谢你。
How do I do this? Thanks.
推荐答案
这是一个字符串数组,不要使用的for..in
,使用香草为
循环:
Itearting over an array:
That's an array of strings, don't use for..in
, use the vanilla for
loop:
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
:
这是为对象的属性,如:
Proper usage of for..in
:
It is meant for object's properties, like:
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
在数组中可能有副作用。请看下图:
Side effects of for..in
with arrays:
Don't take my word for it, let's see why not use it: for..in
in arrays can have side effects. Take a look:
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.
这篇关于我如何引用字符串数组中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文