每日一练 JS30挑战密钥检测

it2026-09-24  12

密钥检测

实现目标

不断读入按键输入判断是否符合定义的密钥

实现逻辑

定义一个空数组每次按键输入便将对应的键值塞入数组,同时维护数组长度检测是否和密钥相同

实现代码

<!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(起始位置,替换个数,替换值)方法可以完成数组的增删改三种需求。数组负值的索引
最新回复(0)