ES6 -Symbol & generator

一、Symbol:数据类型

 定义

let sym=Symbol('aaa');
console.log(sym);//Symbol(aaa)

注意:

1.Symbol不可以new

2.Symbol 返回是一个唯一值,一般用来做一个key,定义一些唯一或私有的内容

3.Symbol是一个单独数据类型,基本类型,typeof 返回 symbol,

4.Symbol作为key,用for in 循环,不会显示

 
let sym=Symbol('aaa');

let json={
    a:'111',
    [sym]:'123'
}
console.log(json[sym]);//123

for(item in json){
    console.log(item);//a
}

 

二、generator:生成器 ,解决异步,深度嵌套的问题

1.语法:

function * test(){
    yield 1;
    yield 2;
    return 3;
}

let res=test();
console.log(res);
// 调用 
console.log(res.next());//{value: 1, done: false}
console.log(res.next());//{value: 2, done: false}
console.log(res.next());//{value: 3, done: false}
console.log(res.next());//{value: undefined, done: false}

 

function * test(){
    let val=yield 'aaa';
    console.log(val);
    yield 'bbb'+val

}
let res=test();
console.log(res.next());//{value: "aaa", done: false}
console.log(res.next('123'));//123  {value: "bbb123", done: false}

 

2. for of 循环 自动遍历generator ,但不会遍历return

 
for(let val of res){
    console.log(val);// 1  2 
}

 

3.generator 与 解构赋值: 不会解构return

 
let [a,b,c]=res;
console.log(a,b,c);//1 2 undefined

 

4.generator 与 扩展运算符: 没有return

let [...a]=res;
console.log(...res);//1 2

 

5.generator与Array.from()

 
console.log(Array.from(res));// [1, 2]

 

 
 
 
 
 
 
 
 

转载于:https://www.cnblogs.com/yuesu/articles/9546286.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值