Currently, I am working on developing a hangman game in JavaScript to enhance my coding skills. One task that I am facing is extracting the keyCode of a character at a particular position within an array. To achieve this, I have been using the 'charCodeAt' method. While this method works flawlessly for obtaining the keyCode of the character at the initial position (position [0]), it fails to update accordingly as it iterates through the array. Subsequently, instead of returning the correct keyCode for subsequent characters, it returns 'NaN' when accessed beyond the first position.
To debug this issue, I implemented 'console.log()' statements to track the values of the characters being displayed and verify that the loop is functioning correctly in terms of index progression. Despite confirming these aspects, the variable responsible for storing the keyCode of the current character fails to capture this information after the second position (position [1]) in the array. Although I feel that there might be redundancy within the code segment causing this problem, I have yet to devise an alternative solution. Just to clarify, both variables referenced are declared globally within the scope.
for(let i=0; i<theArray.length; i++){
indexElementValue = theArray[i];
keyCodeAt = indexElementValue.charCodeAt(i);
inputElement.addEventListener('keydown', validation);
}
const validation = () => {
let typing = event.which || event.keyCode;
if((typing == keyCodeAt) || (typing == 20) || (typing == 32) || (typing == 8) || (typing == 9) || (typing == 13) || (typing == 16)){
}else{
console.warn('WRONG');
}
}
I am hopeful that by resolving the issue with the 'keyCodeAt' variable, it will successfully retrieve and store the correct keyCodes for all positions within the array, rather than only functioning correctly at the first position followed by producing 'NaN' for subsequent positions.