<!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>
<style>
div {
float: left;
border: 1px solid;
width: 100px;
height: 100px;
background-color: rgba(155, 212, 123, .5);
}
</style>
</head>
<body>
<div>run</div>
<div>walk</div>
<div>play</div>
<script>
// 第七种类型 symbol类型 唯一类型
// let a = Symbol();
// let b = Symbol();
//用于定义比对
//例子
// const RUN = 'run';
const RUN = Symbol();
const WALK = Symbol();
const PLAY = Symbol();
// 具有唯一性
// 去除魔术字符串 唯一性
let state = '';
var divs = Array.from(document.querySelectorAll('div'))
// console.log(divs)
divs.forEach(item => {
item.addEventListener('click', clickHandler)
})
function clickHandler(e) {
var index = divs.indexOf(this)
state = index === 0 ? RUN : (index == 1 ? WALK : PLAY)
}
function animation() {
switch (state) {
case RUN:
console.log("run132132");
break;
case WALK:
console.log("walk123123");
break;
case PLAY:
console.log("play123132");
break;
}
}
// 你会发现常量中RUN WALK PLAY 中定义的内容不重要 只要唯一 用于辨识就好了 这个时候 使用symbol就非常合适了
setInterval(animation, 1000);
</script>
</body>
</html>
es6 symbol 用于去除魔术字符串
最新推荐文章于 2023-05-09 11:37:45 发布