Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda