迭代器,iterable, 迭代方法(for...of)
1:在内置对象中带有迭代器的有Array, Set, Map, String, Nodelist对象(DOM的伪数组),arguments(一个对应于传递给函数的参数的类数组对象,非箭头函数);
2:使用迭代器的语法有(a): 遍历语句for...of ,(b):扩展运算符(...)
①:Array的遍历
const arr = [0, 15, 0, -2, "zhangsan", 15];
for (item of arr) {
console.log(item); // 0, 15, 0, -2, zhangsan, 15
}
②:Set的遍历
const arr = [0, 15, 0, -2, "zhangsan", 15];
let mySet=new Set(arr); //集合去重
for (item of Set) {
console.log(item); //0,15,-2,zhangsan
}
③:Map的遍历
const myMap = new Map([
['name', 'Lucas'],
['age', '18'],
['gender', 'male']
]);
///////////////////
for(item of myMap.keys()){
console.log(item) // name ,age ,gender
}
///////////////////
for (item of myMap.values()) {
console.log(item) // Lucas, 18, male
}
/////////////////
for (item of myMap.entries()) {
console.log(item) // ["name", "Lucas"], ["age", "18"], ["gender", "male"]
}
④:String的遍历
const string = "nihao,a"
for (item of string) {
console.log(item) //n i h a o , a
}
⑤:Nodelist对象的遍历
<body>
<h1>nihao</h1>
<h1>a</h1>
<h1>xiaoming</h1>
<script>
var ele = document.querySelectorAll('h1')
for (item of ele) {
console.log(item.innerHTML) // nihao a xiaoming
}
</script>
</body>
⑥:函数arguments的遍历
function foo(a, b, c, ...d) {
console.log(arguments); //Arguments(7) [1, 2, 3, 4, 5, 6, 7, callee: (...), Symbol(Symbol.iterator): ƒ]
console.log(arguments[6]) // 7
}
foo(1, 2, 3, 4, 5, 6,7);
浙公网安备 33010602011771号