JS17 -- 循环和遍历各方法比较

1、for...in:

  ①. 返回下标
  ②. 只遍历可枚举的,如果设置某下标为不可枚举,则不展示Object.defineProperty(arr,index,{enumrable:false})
  ③. 还会遍历继承的, Array.prototyp.my = 'shabi'; 也会遍历出来,可以通过hasOwnProperty判断有没有这个属性(非继承)
  ④. 对象遍历不安顺序{"2":'ef',"a":'fefe',"1":"feffgeef"}
  ⑤. 数组通过对象方式添加属性,array.text = 1;只有for...in能打印出
2、forEach:

   ①. 返回值,下标,原数组
  ②. 没办法使用 break 语句跳出循环,或者使用return从函数体内返回
3、for...of

  ①. 返回值
  ②. 获取下标转为Map
  ②. 可以使用 break, continue 和 return
  ③. 除支持数组,还支持字符串,Set,Map(let [key,value] of xxxMap),对象
  ⑤. 代替for...in和forEach

Array.prototype.bb = 'efefef';
let arrA = [
	{id:1, name: 'AA', url: '/ueijfejf'},
	{id:2, name: 'BB', url: '/ueijfejf'},
	{id:3, name: 'CC', url: '/ueijfejf'},
	{id:4, name: 'DD', url: '/ueijfejf'},
	{id:5, name: 'EE', url: '/ueijfejf'},
]
arrA['efefe'] = {id:0}
Object.defineProperty(arrA,'efefe',{
	enumerable: false
})
Object.defineProperty(arrA,0,{
	enumerable: false
})
Object.defineProperty(arrA,2,{
	enumerable: false
})
console.log('for...in-start')
for(let item in arrA){
	console.log(item);
}
console.log('for...in-end')
console.log('forEach-start')
arrA.forEach((item)=>{
	console.log(item)
})
console.log('forEach-end')
console.log('for...of-start')
for(let item of arrA){
	console.log(item);
}
console.log('for...of-end')

  JS17 -- 循环和遍历各方法比较_第1张图片

 4、filter 

 过滤数组

 arr.filter((item,index,oldArr)=>{true});   //   return 为true的item,生成新的数组,否则[]

5、map 

 arr.map((item,index,oldArr)=>{  }); 

https://segmentfault.com/a/1190000018340362

https://www.cnblogs.com/qdlhj/p/9916324.html
https://www.baidu.com/s?ie=UTF-8&wd=map%20%E5%92%8C%20for%20of

你可能感兴趣的:(JS17 -- 循环和遍历各方法比较)