2个快速问题
伪码
var arr = [3, 5, 7];
var pos, value;
for (pos in arr) {
console.log(pos); // logs "0", "1", "2"
}
for (value of arr) {
console.log(value); // logs "3", "5", "7"
}发布于 2015-09-12 09:28:50
只需在原始数组上使用索引,就可以获得for in的值:
var arr = [3, 5, 7];
var pos, value;
for (pos in arr) {
console.log(arr[pos]); // logs 3, 5, 7
}注意,使用for...in迭代数组是一个不良做法。
在for…of中获取索引需要一个外部计数器:
var arr = [3, 5, 7];
var pos = 0, value;
for (value of arr) {
console.log(pos++); // logs 0, 1, 2
}两种情况下更好的解决方案是Array.prototype.forEach。
arr.forEach((value, index) => {
console.log('index: ', index);
console.log('value: ', value);
});发布于 2015-09-12 09:33:01
有一种方法:
for (let [key, value] of arr.entries()) {
// ...
}它使用Array.prototype.entries(),它在(key; value)和阵列破坏的元组上返回一个迭代器,将其转换为两个分离的变量。
要特别指出您的答案:当您遍历数组时,您应该使用for (var i = 0; i < arr.length; ++i)或for-of,for-in。
发布于 2015-09-12 09:27:55
使用for...in
for (pos in arr) {
console.log(arr[pos]);// logs "3", "5", "7"
}没有办法使用for...of。这会给你一个主意。
var arr = ["3", 3, {}, true];
for (value of arr) {
console.log(typeof value);
}https://stackoverflow.com/questions/32537201
复制相似问题