目录
3. Number.isFinite() 与 Number.isNaN()
3. Number.parseInt() 与 Number.parseFloat()
一、迭代器
遍历器(Iterator
)就是一种机制。它是一种接口,为各种不同的数据结构提供统一的访问机
制。任何数据结构只要部署 Iterator
接口,就可以完成遍历操作。
1.ES6
创造了一种新的遍历命令
for...of
循环,
Iterator
接口主要供
for...of
消费
2.
原生具备
iterator
接口的数据
(
可用
for of
遍历
)
- Array
- Arguments
- Set
- Map
- String
- TypedArray
- NodeList
以上数据会具备图片中标注出的属性 :
//声明一个数组
const name = ["Tom","Jack","Bob"]
//使用for of 遍历数组
for(let v of name){
console.log(v); //v输出遍历的数组内容
}
// for(let v in name){
// console.log(v); //v输出数组下标
// }
3.
工作原理
- 创建一个指针对象,指向当前数据结构的起始位置
- 第一次调用对象的 next 方法,指针自动指向数据结构的第一个成员
- 接下来不断调用 next 方法,指针一直往后移动,直到指向最后一个成员
- 每调用 next 方法返回一个包含 value 和 done 属性的对象
//声明一个数组
const name = ["Tom","Jack","Bob"]
let iterator = name[Symbol.iterator]()
//调用对象的next方法
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
注 : 需要自定义遍历数据的时候,要想到迭代器
迭代器自定义遍历对象案例
let person = {
name:"Tom",
hobby:[
"basketball",
"football",
"dance",
"rap"
],
[Symbol.iterator](){
//索引变量
let index = 0;
let _this = this;
return {
next:function(){
if(index<_this.hobby.length){
const result = {
value:_this.hobby[index],
done:false
}
//下标自增
index++;
//返回结果
return result;
}else{
return{
value:undefined,
done:true
}
}
}
}
}
}
//遍历这个对象
for(let v of person){
console.log(v);
}
二、生成器
生成器函数是 ES6
提供的一种
异步编程解决方案
,语法行为与传统函数完全不同
//生成器其实就是一个特殊的函数
function * gen(){
console.log("hello generator");
}
let iterator = gen();
iterator.next() //hello generator
//yield 函数代码的分隔符
function * gen(){
console.log(111);
yield 'Hello';
console.log(222);
yield 'Good';
console.log(333);
yield 'Morning';
console.log(444);
}
let iterator = gen();
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
for(let v of gen()){
console.log(v);
}
代码说明:
- * 的位置没有限制
- 生成器函数返回的结果是迭代器对象,调用迭代器对象的 next 方法可以得到 yield 语句后的值
- yield 相当于函数的暂停标记,也可以认为是函数的分隔符,每调用一次 next 方法,执行一段代码
- next 方法可以传递实参,作为 yield 语句的返回值
生成器函数的参数
function * gen(arg){
console.log(arg);
let one = yield '111'
console.log(one);
let two = yield '222'
console.log(two);
}
//执行获取迭代器对象
let iterator = gen('AAA')
console.log(iterator.next());
//next方法可以传入实参
console.log(iterator.next("BBB"));
console.log(iterator.next("CCC"));
生成器函数的两个实例:
1.解决回调地狱</