0
Getting the code of a key and keeping it in an array (please help)
Hello, I have to write a code that gets the key code of a pressed key then check if it isn't in an array and if it isn't - to add it or if it already is, to remove the exact same code of the key and all of this should be in a function. The problem is - I know what to do, but I don't know how to write the code. Can someone help me please and show me an example or tell me what to use?
2 ответов
+ 3
Use indexOf to check if the key if already in the array.
if (arr.indexOf(key) == -1){
the key is not there
arr.push(key)
}
else{
key is there now use "for" to loop through the array and when you find the key use the "splice" method to remove it based on its position(index)
}
+ 2
If your JS engine isn't too old, you could get benefits of using the Set object, wich is designed to store unique values (be careful that in this context 42 != "42"):
var keys = new Set();
function addKey(code) { keys.add(code); }
If a value is already in the set, the add() method will do nothing (automatic check is done for you, and more efficiently that with an array)...
If you need the set as an array at any time, you could use:
var keyArr = [...keys];
... or iterate over it with a for...of loop ;)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set