Symbol:
定义:let syml = Symbol ('aaa');
注意点:
1,Symbol 不能new
2,Symbol() 返回是一个唯一值
所以也可以作为一个key,定义一些唯一或者私有的一些东西
3,typeof可以检测的类型从number,string,boolean,object,function,undefined这六种类型变成了还有symbol的7种
4,symbol是一个单独的数据类型,就叫symbol,不能再拆分
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
</head>
<body>
</body>
<script>
let syml = Symbol('ReSword');
let json = {
a: 'apple',
b: 'orange',
[syml]: 'aaa'
};
for (let item in json) {
console.log(item);
}
console.log(json['a']);
console.log(json[syml]);
</script>
</html>
在这里是把syml当做一个私有属性,所以在for in 循环中是无法循环到的
-------------------------------------------------------------------------------------------------------
generator函数
主要解决的问题:解决异步
语法:
这样show函数就是generator函数
和yield配合使用声明
调用方式:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
</head>
<body>
</body>
<script>
function * show () {
yield 'hi';
yield 'ReSword';
return 'hi ResSord'
}
let g1 = show();
console.log(g1);
console.log(g1.next());//{value: "hi", done: false}
console.log(g1.next());//{value: "ReSword", done: false}
console.log(g1.next());//{value: "hi ResSord", done: true}
console.log(g1.next());//{value: undefined, done: true}
</script>
</html>
这个调用是手动调用的
for of 调用
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
</head>
<body>
</body>
<script>
function * show () {
yield 'hi';
yield 'ReSword';
return 'hi ResSord'
}
let g1 = show();
for (let item of g1) {
console.log(item);
}
</script>
</html>
但是return的内容不会遍历
gererator函数返回的是一个对象,所以也可以用解构赋值,将里面的内容解构出来
也可以使用扩展运算符
结合axios来使用generator函数
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
</body>
<script>
//https://api.github.com/users/ReSword
function * gen () {
let username = yield 'ReSword';
yield axios.get(`https://api.github.com/users/${username}`);
}
let g1 = gen();
let username = g1.next().value;
console.log(username);
// console.log(g1.next(username).value);
g1.next(username).value.then((res) => {
console.log(res.data)
});
</script>
</html>
其中g1.next(username).value返回的一个Promise对象,所以要配合then使用