标签:-o set 遍历数组 下标 var index length key值 for循环
1、普通for循环 (遍历数组的索引值(下标),边界可以自己划定)
var arr = [10, 20, 30];
for(var i=0; i<arr.length; i++)
console.log(arr[i]); //10 20 30
2、for-in 循环(遍历数组或者对象的索引值(key值))
var arr = [10, 20, 30];
var obj = {
"a": 40,
"b": 50,
"c": 60
};
var i;
for(i in arr){
console.log(i); //0 1 2
console.log(arr[i]); //10 20 30
}
for(i in obj){
console.log(i); //"a" "b" "c"
console.log(obj[i]); //40 50 60
}
3、for-of循环(不适用于对象,遍历得到Set、Map、数组的value)
var arr = [10, 20, 30];
var set = new Set([40, 50, 60]);
var map = new Map([
["a", 10],
["b", 20],
["c", 30]
]);
var val;
for(val of arr)
console.log(val); //10 20 30;
for(val of set)
console.log(val); //40, 50 60
for(val of map)
console.log(val); //["a": 10] ["b": 20] ["c": 30]
4、forEach 循环 (不适用于对象)
var arr = [10, 20, 30];
var set = new Set([40, 50, 60]);
var map = new Map([
["a", 10],
["b", 20],
["c", 30]
]);
arr.forEach((val, index, ele) => {
console.log(index + ":" + val); //0:10 1:20 2:30
console.log(ele) //[10,20,30] ~ ~
})
set.forEach((val, index, ele) => {
console.log(index + ":" + val); //40:40 50:50 60:60
console.log(ele) //Set(3) {40, 50, 60} ~~~ ~~~
})
map.forEach((val, index, ele) => {
console.log(index + ":" + val); //"a":10 "b":20 "c":30
console.log(ele) //Map(3) {"a" => 10, "b" => 20, "c" => 30} ~~~~ ~~~~
})
标签:-o set 遍历数组 下标 var index length key值 for循环
原文地址:https://www.cnblogs.com/lianchenxi/p/9600472.html