What is the method for utilizing keycodes inside an array to determine which keys are recognized as input in a 'keyup' event listener?

I'm currently working on creating a game similar to Wordle, but I've hit a roadblock when it comes to filtering out only the alphabet keys as valid keyboard inputs for the game.

Within my Keyboard container, I have rows of keys and a JavaScript file that I can't seem to progress in:

// Keyboard
// Listen for key being released
let key_codes = [81,87,69,82,84,89,85,73,79,80,
                  65,83,68,70,71,72,74,75,76,
                  13,90,88,67,86,66,78,77,8];
document.addEventListener('keyup', (e) => {
    if (e.keyCode in key_codes) {
        console.log(e.keyCode);
    }
});

I've compiled a list of acceptable keycodes for the game and attempted to set up an event listener to monitor key releases. However, when I check 'if (e.keyCode in key_codes)', I'm not getting any output despite expecting one.

I've verified the types of list elements and keyCodes (they match), and even tried printing 'e.keyCode' before the if statement, which correctly displays the pressed key. Despite this, I can't seem to identify what's causing the issue.

There might be something simple I'm overlooking here, but unfortunately, I haven't been able to solve it yet.

Answer №1

Using the in keyword in JavaScript is different from its use in Python. In JavaScript, in is used to check if an object has a specific property. To achieve a similar functionality like Python's in, you can use the Array.prototype.includes function instead. Learn more about the 'in' keyword

Here's how you can utilize the Array.prototype.includes function to check for the first occurrence of an element in an array and determine if it exists or not:

let key_codes = [81,87,69,82,84,89,85,73,79,80,
                  65,83,68,70,71,72,74,75,76,
                  13,90,88,67,86,66,78,77,8];
document.addEventListener('keyup', (e) => {
    if (key_codes.includes(e.keyCode)) {
        console.log(`${e.keyCode} is in the array`);
    } else console.log(`${e.keyCode} is not in the array`);
});

Feel free to run the above code and test it out yourself!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve data in a flattened format from MongoDB

I have multiple nested collections stored in my MongoDB database. Upon executing the query below on my server: AggregatedData .aggregateAsync([{ $match: { "_id.date": { $gte: dateFrom, $lte: dateTo } } }, { $project: { "date ...

What is the method for identifying the environment within an Express.js application?

Is there a reliable method for determining the environment in which an expressJS app is currently operating (development, test, production)? I have checked process.env, but found no clear indication of the environment. I know that variables can be set in ...

Encountered an issue with ReactJS app authentication using Firebase and FirebaseUI. Error message reads: "Uncaught Error: Firebase App named '[DEFAULT]-firebaseui-temp' already exists

I'm currently facing an issue in my code. I am working on a single-page web application in ReactJS with 3 tabs. Whenever the user navigates to one tab, the authentication form from FirebaseUI should appear. However, there seems to be a problem as it ...

Error message: "django.utils.datastructures.MultiValueDictKeyError - The specified key was

When I submit a form without using ajax, everything works perfectly. However, when I try to submit the form using ajax, I encounter the following error: django.utils.datastructures.MultiValueDictKeyError: Here are the HTML form codes that work without aj ...

Despite the fact that the toggle button in React is designed to function properly, it is currently not working as

Check out step #2 of this challenge where a toggle button is used to switch between displaying monthly and yearly values. Here's the accompanying code: import { NavLink } from "react-router-dom"; import { useContext } from "react"; ...

Check if the <ion-content> in Angular Ionic has reached the bottom when scrolling

I'm in the process of developing a messaging app using Angular and Ionic. I want to trigger the scrollToBottom method only when it is scrolled to the very bottom. This way, if someone scrolls to the top to read old messages while their partner sends a ...

Exploring the Capabilities of Drag-and-Drop Functionality in jsTree and DataTables

Is it possible to copy nodes from a jsTree that I've dragged to a cell in a DataTable? I'm struggling with getting this functionality to work. Any suggestions on how to achieve this? I am not seeing any alerts appear. This is the HTML code: &l ...

What could be causing the returned promise value to not refresh?

I am currently facing an issue with my program. Upon clicking a button, the goal is to update the "likes" attribute of a MongoDB document that has been randomly fetched. Despite setting up the logic for this, the update does not occur as intended: MongoCli ...

Tips for positioning a button next to a text area

I am facing an issue with aligning my text area and button vertically on the same line. Despite my attempts, the button keeps getting pushed downwards. Can someone please provide me with a solution to align them properly? Thank you. Here is the HTML code ...

"Revolutionary jQuery plugin designed to function independently of HTML elements

Is it possible to create a jQuery plugin that can be executed without the use of an element selector? Typically, we use: $('#myElementID').myPluginFunction(myVariables); But, is there a way to do it like this instead? $.myPluginFunction(my ...

An unusual occurrence involving JQ selectors and various variable labels

Looking to incorporate mouseover and mouseout functions into a series of classes, I decided to use jQuery selectors with variables in a loop: for(i=1; i<=2; i++){ cid = '.Cid'+i; ccid = '.CCid'+i; csid = '.CSid&apo ...

Generating a JSON Array by aggregating data from a loop with the help of the Spring Boot framework

Recently, I successfully implemented a code to import data from a .pcap file. The code works flawlessly as it reads the cap files and displays the results in the console. The implementation of this code can be seen below: @SpringBootApplication public cl ...

Is it possible to load a .js file in one UIWebview and then utilize it in multiple instances of UIWebviews in iOS?

I am currently developing an iOS app that displays multiple charts in several UIWebviews using a JavaScript Library. The app sends data to the JS library, which then renders the charts based on the provided data. The main issue I am facing is that each we ...

Extracting information from a dynamic webpage using Selenium and jSoup technology

Recently, I have been inquiring about a method to gather all the matches from a specific webpage but have not yet found a suitable solution. My goal is to extract information such as time, home team, and away team from which loads its content dynamically ...

How come my uploaded Excel Javascript add-on opens in an external browser instead of the task pane?

Note: It has come to my attention that I must save the taskpane.html file on my local drive before it opens in an external browser. This detail slipped my notice last week. I am currently developing a Javascript, or rather Typescript, API add-in for Excel ...

TypeScript error: Unable to locate namespace 'ng'

I am attempting to utilize a tsconfig.json file in order to avoid having /// <reference tags at the beginning of multiple files. However, I keep encountering this error: [ts] Cannot find namespace 'ng'. any Here is my configuration within ...

Is there a way to use JavaScript to alter the CSS properties of sibling elements that are adjacent to each other

I am trying to modify the CSS style of directly adjacent siblings when hovering over an element. For example, if I hover over element 4, elements 3 and 5 should have a new CSS class applied. Check out my JSfiddle to see the expected result and what I have ...

Backend JS error found in Joomla 3.0 Component

Currently, I am working on developing a custom Joomla 3.0 component. To begin, I started by downloading the com_hello component sample from the official Joomla documentation. However, I've encountered an issue when trying to check the checkbox in the ...

JavaScript array reformatting executed

I have an array object structured like this. [ {student_code: "BBB-002-XRqt", questions: "Length (in inches)", answer: "8953746", time: "00:00:08:15"}, {student_code: "CCC-003-TYr9", questions: "He ...

Webpack 5 is unable to load animated gif files

Hello, I am currently diving into webpack and following the official documentation at https://webpack.js.org/guides/asset-management/#setup. My goal is to incorporate an animated gif using webpack 5. Although the placeholder for the gif is loading, I enco ...