1、创建Symbol
//创建Symbol
let s = Symbol();
//s1 === s2 false
let s1 = Symbol('a');
let s2 = Symbol('a');
//s3 === s4 true
let s3 = Symbol.for('b');
let s4 = Symbol.for('b');
2、不能与其他数据运算
let s = Symbol();
//报错
let result = s + 100;
let result = s + s;
let result = s > 100;
3、总结一下JS的数据类型
usonb 记:you are so niubility
u:undefined
s:string Symbol
o:object
n:null number
b:Boolean
4、向对象添加Symbol类型的属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 向对象中添加方法 up down
let game = {
name: '俄罗斯方块',
up: function() {},
down: function() {}
};
// 声明一个对象
// let methods = {
// up: Symbol(),
// down: Symbol()
// };
// game[methods.up] = function() {
// console.log("i can change the size");
// }
// game[methods.down] = function() {
// console.log("i can down");
// }
// console.log(game);
let youxi = {
name: "狼人杀",
[Symbol('say')]: function() {
console.log("我可以发言");
},
[Symbol('zibao')]: function() {
console.log('wokeyizibao');
}
}
console.log(youxi);
</script>
</body>
</html>
5、Symbol的内置属性:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// hasInstance属性
// class Person {
// static[Symbol.hasInstance](param) {
// console.log(param);
// console.log("我被用来检测类型了");
// }
// }
// let o = {};
// console.log(o instanceof Person);
// isConcatSpreadable属性
const arr = [1, 2, 3];
const arr2 = [4, 5, 6];
arr2[Symbol.isConcatSpreadable] = false;
console.log(arr.concat(arr2));
</script>
</body>
</html>
迭代器iterator
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 声明一个数组
const xiyou = ['唐僧', '孙悟空', '猪八戒', '沙僧'];
let iterator = xiyou[Symbol.iterator]();
// 调用对象next方法
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
</script>
</body>
</html>
迭代器应用,自定义遍历数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 声明一个对象
const banji = {
name: "终极一班",
stus: [
'xiaoming',
'xiaoning',
'xiaotian',
'lili'
],
[Symbol.iterator]() {
// 索引变量
let index = 0;
let _this = this;
return {
next: function() {
if (index < _this.stus.length) {
const result = {
value: _this.stus[index],
done: false
};
index++;
return result;
} else {
return {
value: undefined,
done: true
};
}
}
}
}
}
// 遍历这个对象
for (let v of banji) {
console.log(v);
}
</script>
</body>
</html>