密钥检测
实现目标
不断读入按键输入判断是否符合定义的密钥
实现逻辑
定义一个空数组每次按键输入便将对应的键值塞入数组,同时维护数组长度检测是否和密钥相同
实现代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Key Detection
</title>
<script type="text/javascript" src="http://www.cornify.com/js/cornify.js"></script>
</head>
<body>
<script>
const secretCode = 'arvin';
const pressed = [];
window.addEventListener('keyup', (e) => {
console.log(e.key);
pressed.push(e.key);
pressed.splice(-pressed.length-1,pressed.length - secretCode.length);
console.log(pressed.join(''));
if (pressed.join('').includes(secretCode)) {
console.log('Yeh, HU HU!');
cornify_add();
}
})
</script>
</body>
</html>
总结
数组的splice(起始位置,替换个数,替换值)方法可以完成数组的增删改三种需求。数组负值的索引