Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

141
Vistas
How to loop through a JavaScript array based on key.event?

I'm a newbie messing around with event listener/handlers and generally just getting to grips with some JS (first post on StackOverflow!)

I'm making a simple webpage that changes backgroundColor based on user input (alpha characters only). The user presses a letter key and the page will update to a color with a match on the first letter. It will also print the name of the color to the page.

I have a large array storing names of CSS colors, most keys have multiple colors that match the keystroke/first letter of the color, and some keys have no matches.

My code below hopefully explains my intentions, however I can't quite get it to work.

const colors = ["Aquamarine", "Alice Blue", "Antiquewhite", "Aqua", "Azure"] etc etc...

// Returns a random colour from the colour arrays
const randomiser = colorArr => {
    return colorArr[Math.floor(Math.random()*colorArr.length)];
}

// Event listener
window.addEventListener("keypress", e => {
    let colorsMatchingKeyName = [];

    function colorFinder(arr) {
        let keyName = e.key;
        for (let i = 0; i < arr.length; i++) {
            if (arr[i].charAt(0) !== keyName) {
                document.getElementById('currentColor').innerHTML = `Sorry! No colours match up with the ${keyName} key!`; 
            } else if (arr[i].charAt(0) == keyName) {
                colorsMatchingKeyName.push(arr[i]);
            } 
        }
    }

    colorFinder(colors);

    // Logging colors to console to test.
    console.log(colorsMatchingKeyName) // outputs an empty array

    
    // Once it is working i'll use the randomiser() function to pick a 
    // random colour from the colorMatchingKeyName array and set the document.style.backgroundColor
})

At present, each key event only prints the 'Sorry! No colours...' message shown in the if statement.

I'd be hugely grateful if someone could please direct me to the issue in my code!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You might want to check this out:

const colors = ["Aquamarine", "Alice Blue", "Antiquewhite", "Aqua", "Azure"]

// Returns a random colour from the colour arrays
const randomiser = colorArr => {
    return colorArr[Math.floor(Math.random()*colorArr.length)];
}

// Event listener
window.addEventListener("keypress", e => {
    let colorsMatchingKeyName = [];

    function colorFinder(arr) {
        let keyName = e.key;
        document.getElementById('currentColor').innerHTML = '';
        for (let i = 0; i < arr.length; i++) {
        const c = arr[i].charAt(0).toLowerCase();

        if (c !== keyName.toLowerCase()) {
                document.getElementById('currentColor').innerText = `Sorry! No colours match up with the ${keyName} key!`; 
            } else if (c == keyName) {
                colorsMatchingKeyName.push(arr[i]);
            } 
        }
    }

    colorFinder(colors);
    const color = randomiser(colorsMatchingKeyName);
    console.log(color)

    document.body.style.backgroundColor = color;
})
<div id="currentColor"></div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda