我使用javascript编写了此代码:
var arr = [
'one',
'two',
'three',
'four',
'five'
];
for (var property1 in arr) {
console.log(property1);
}
执行此代码时,我得到:
'1'
'2'
'3'
'4'
但是我想要这个:
'one',
'two',
'three',
'four',
'five'
我该如何使用for循环?
非常感谢您!
答案 0 :(得分:2)
像下面一样使用for..of
var arr = [
'one',
'two',
'three',
'four',
'five'
];
for(var property1 of arr) {
console.log(property1);
}
答案 1 :(得分:1)
欢迎您!
如果要遍历数组,则需要使用for..in
以外的其他内容。您可以使用for..of
或for
循环,但是最好理解为什么会这样。
for..in
遍历对象的键/值对。括号中的变量被设置为该键/值对的key
。对于数组,它将被设置为数组的索引或任何可枚举的属性。这就是为什么它打印数字而不是单词的原因。
我还想指出一些迭代方法,这些方法可能在命令式循环之外有用。
arr.forEach
将允许您遍历数组,而无需使用额外的for
语法。
arr.forEach(item => console.log(item))
arr.map
和arr.filter
之类的其他方法在您开始遍历列表时会赋予您更多功能。
const numbers = [1,22,11,18,16];
const add = a => b => a + b;
const isEven = number => number %2 === 0;
const biggerEvenNumbers = numbers
.map(add(1))
.filter(isEven) // [2,12]