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

for...in:

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

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

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

filter 

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')

  

https://segmentfault.com/a/1190000018340362

猜你喜欢

转载自www.cnblogs.com/lgyong/p/12704162.html