Navigate back to the homepage

Day12: Key Sequence Detection

JavaScript30
July 5th, 2021 · 1 min read

專案介紹: 按下密碼後,在頁面顯示一些驚喜的圖片。

作品頁面: https://iris1114.github.io/javascript30/12_Key-Sequence-Detection/

code

1const pressed = [];
2const secretCode = "ok";
3
4window.addEventListener("keyup", (e) => {
5 //把按下的鍵盤元素加入陣列
6 pressed.push(e.key);
7
8 //透過運算使pressed陣列長度始終與設定密碼相同,且當超出時替換掉陣列第一個元素
9 pressed.splice(-secretCode.length - 1, pressed.length - secretCode.length);
10 //判斷輸入值陣列的內容是否與設定密碼相同
11 if (pressed.join("").includes(secretCode)) {
12 cornify_add();
13 }
14});

補充

splice()

splice(start, deleteCount, item1, item2, ...)可以對陣列內容過行刪除或新增。

start: 陣列中要開始改動的元素索引 delete: 一個表示欲刪除的原陣列元素數量的整數 item1, item2, ...: 從 start 開始,要加入到陣列的元素。

1const months = ["Jan", "March", "April", "June"];
2months.splice(1, 0, "Feb"); //["Jan", "Feb", "March", "April", "June"]
3
4const arr = [1, 2, 3];
5arr.splice(0, 1); //[2,3]

join()

arr.join([separator]) , 會將陣列中所有的元素連接、合併成一個字串,並回傳此字串。

separator:如果未傳入此參數,陣列中的元素將預設用英文逗號(「,」)隔開。如果 separator 是空字串,合併後,元素間不會有任何字元。

1const elements = ["Fire", "Air", "Water"];
2
3console.log(elements.join());
4// expected output: "Fire,Air,Water"
5
6console.log(elements.join(""));
7// expected output: "FireAirWater"
8
9console.log(elements.join("-"));
10// expected output: "Fire-Air-Water"

includes()

arr.includes(searchElement[, fromIndex]) 方法會判斷陣列是否包含特定的元素,並以此來回傳 true 或 false。

1const pets = ["cat", "dog", "bat"];
2
3console.log(pets.includes("cat"));
4// expected output: true
5
6console.log(pets.includes("at"));
7// expected output: false

參考資料

https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/includes https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/join https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

More articles from Iris Blog

Day11: Custom Video Player

客製化player播放器,功能包含播放、暫停、音量、速度、快進、快退、全螢幕。

July 3rd, 2021 · 1 min read

Day10: Hold Shift and Check Checkboxes

按住 Shift 鍵對多個 checkbox 進行勾選。

July 1st, 2021 · 1 min read
© 2020–2021 Iris Blog
Link to $mailto:qweichew@gmail.comLink to $https://github.com/iris1114Link to $https://www.instagram.com/iris.justdoit/Link to $https://www.linkedin.com/in/iris-chew