js中常用的遍历方法
记录一下js中常见的遍历方法,以免突然想不起
常见的需要遍历的目标
// 数组
var a = [ 1, 2, 3 ];
// 数组含对象
var b = [ {a:1}, {b:2}, {c:3} ];
// 纯对象
var obj = { a:1, b:2, c:3 };
1、for(let ; ; ) 最常见的用法
这个用法可以解决大部分遍历问题
for(let i = 0 ; i < a.length; i++ ){
console.log(a[i]); // 1,2,3
}
2、for( let … in … ) 只有这个才能直接遍历对象
遍历hash数组,或者类数组对象
也可以遍历数组,但意义不大
for(let key in obj){
console.log(key); // a,b,b
console.log(obj[key]); // 1,2,3
}
3、forEach() 遍历
(我有同事跟我说这是es6语法,但是其实不是,但我确实用的不多)
b.forEach((item, index)=>{
console.log(item); // {a:1},{b:2},{c:3}
console.log(index); // 0, 1, 2
})
/es6语法/
// 4、 for(let … of … ) 对象无法直接遍历
// 例子1 数组
for(let item of a){
console.log(item); // 1,2,3
}
// 例子2 数组含对象
for(let item of b){
console.log(item); // {a:1},{b:2},{c:3}
}
// 例子3 数组含对象 遍历出value
for(let item of b.values() ){
console.log(item); // {a:1},{b:2},{c:3}
}
// 例子4 数组含对象 遍历出key
for(let index of b.keys() ){
console.log(index); // 0,1,2
}
// 例子5 数组含对象 遍历出value和index
for(let [item, index] of b.entries() ){
console.log(item); // {a:1},{b:2},{c:3}
console.log(index); // 0,1,2
}
没了