JS学习笔记之数组遍历方法总结
数组遍历的方法有很多,感觉最基本的方法有些死板,所以总结了比较好用的方法。
1.原始方法
var a=[1,2,3,4]; for(var i=0;i<a.length;i++){ console.log(a[i]); } 结果为:1 2 3 4
2. for in
var a=[1,2,3,“hello”,“world”]; for(let i in a){ console.log(a[i]); } 结果和预想的一样
for in还有另外一种,对enumerable对象的操作: var b={a:1,b:2,c:3,d:“hello”,e:“world”}; f or(let index in b){ console.log(index,b[index]); }
3.forEach
var a=[1,2,3,“hello”,“world”]; a.forEach(i=>{ console.log(i); }) 或者这样写: a.forEach(function(i){ console.log(i); });
4.for of
let s="helloworld";
for(let c of s){
console.log(c);
}