关于遍历一个数组的几种方法比较

来源:互联网 发布:怎么做时间轴java 编辑:程序博客网 时间:2024/06/01 09:27
复制代码
复制代码
 <!doctype html> <html lang="en"> <head> <title>Document</title> </head> <body>      <script>           var arr=[1,4,56,7,7,8,8,,9,,9,9,,9,9];           var obj={name:"eval",age:23,sex:""};           //只能遍历索引数组。           for(var  j=0,len=arr.length;j<len;j++){                 console.log(arr[j]);           }
复制代码

  //for...in 是遍历对象的健名,或者数组的下标(数组,对象都可用)

  存在的问题:1)在某些情况下,这段代码可能按照随机顺序遍历数组元素,

             2)数组原型链上的属性都能被访问到  

复制代码
Array.prototype.a=123;
Array.prototype.foo=function(){};
var arr=[2,3];
for(let k in arr){ console.log(arr[k]);//2,3,123,function()}
但是我们可以进行过滤处理(也不是很麻烦)
for(let k in arr){
  arr.hasOwnProperty(k)&& console.log(arr[k]);
}
复制代码

总之:for-in是为普通对象设计的,你可以遍历得到字符串类型的键,因此不适用于数组遍历

复制代码
for(var i in arr){    console.log(arr[i]);}for(var i in obj){    console.log(i);}

//for …of….遍历数组的键值,不能遍历对象,但是可以遍历类数组对象(也是数组),还可以用来遍历一个字符串(它将字符串视为一系列的Unicode字符来进行遍历:)for(let value of arr){ console.log(value);}利用for....of....遍历一个字符串for(var chr of "abcdefr"){  console.log(chr);} 结果:a,b,c,d,e,f,r
//js中forEach只能遍历数组,不能遍历对象
存在的问题:不能使用break语句中断循环,也不能使用return语句返回到外层函数。
arr.forEach(function(e){ console.log(e); });//js中的forEach只是支持对数组的遍历,不支持对对象的遍历 /* obj.forEach(function(e){ console.log(e); }); *///arr.map只能遍历数组 arr.map(function(v,i){ console.log(v,i); }); arr.map((v,i)=>(console.log(i,v)));   var list = new Map().set('a',1).set('b',2).set('c',3);   console.log(list);   for (var [key,value] of list) {     console.log(key + ' => ' + value);   }
</script> </body></html>
复制代码

 

  

复制代码