ES6 迭代器、以及(for...in、for...of、forEach、map的区别和共同点)

迭代器

迭代器(lterator)是一种接口,为各种不同的数据结构,提供统一的访问机制。
任何数据结构只要部署迭代器(lterator),就可以完成遍历操作

1). ES6创造了一种新的遍历命令for…of循环,lterator 接口主要供for…of消费
2). 原生具备lterator 接口的数据(可用for…of遍历)

Array
Arguments
Set
Map
String
TypedArray
NodeList

for…in、for…of、forEach的区别和共同点

for…of 一般用来遍历 “ 数组(或类数组)” (不可以遍历对象,会报错)

for…of 会对数组中的每一项进行遍历,并返回数组每一项的值

const arr = ["rookie", "theshy", "ning", "puff", "boolean"]
for (const value of arr) {
    console.log(value)
}
// rookie  theshy  ning  puff  boolean

for…in 一般用来遍历 “ 对象 ”(也可以遍历数组,但只返回index值)

遍历对象

const objIG = {
    number: "5",
    mid: "rookie",
    top: "theshy",
    jg: "ning",
    adc: "puff",
    sup: "boolean"
}
for (const key in objIG) {
    // 输出key值,  键名 number mid top jg adc sup
    console.log(key) 
    // 输出value值,键值 5 rookie theshy ning puff boolean
    console.log(objIG[key])
}

遍历数组

const arr = ["rookie", "theshy", "ning", "puff", "boolean"]
for (const key in arr) { 
	// 返回 index 0 1 2 3 4 
    console.log(key)
    // 返回 值  rookie, theshy, ning, puff, boolean
    console.log(arr[key])
}

forEach 、map

相同点:
1 .都是循环遍历数组中的每一项
2 .forEach和map方法里每次执行匿名函数都支持3个参数,参数分别是item(当前每一项),index(索引值),arr(原数组)
3 .匿名函数中的this都是指向window
4 .只能遍历数组
5 .都不会改变原数组

区别:
map方法
1 .map方法返回一个新的数组,数组中的元素为原始数组调用函数处理后的值。
2 .map方法不会对空数组进行检测,map方法不会改变原始数组。

const arr = ["rookie", "theshy", "ning", "puff", "boolean"]
const newArr = arr.map(function (currentValue, index, arr) {
    return index + 1 + ":" + currentValue
});
// (5) ["1:rookie", "2:theshy", "3:ning", "4:puff", "5:boolean"]

猜你喜欢

转载自blog.csdn.net/qq_40893035/article/details/108273791