Sura Rzayeva
Sura Rzayeva

Reputation: 21

Why does 'for' loop only returns the last item in the array?

I'm a newbie in JavaScript and I'm trying to do simple exercises everyday. Can you please explain me why, my for loop only returns the last item in my array? Thanks a lot in advance! The code is:

let button = document.querySelector ('.button');
let background = document.querySelector ('body');
let colors = ['black', 'blue', 'green', 'white', 'brown', 'yellow'];


button.addEventListener ('click', function(){
    for (let i= 0; i< colors.length; i++) {
    let index = colors [i];
    background.style.backgroundColor = index;
    }
})

P.S. I also tried it like: background.style.backgroundColor = colors[i]; (without adding index variable). Still i get only the last color, which is yellow.

Upvotes: 1

Views: 2465

Answers (5)

Mister Jojo
Mister Jojo

Reputation: 22265

Same answer with ES7 code

const delay  = ms => new Promise(res=>setTimeout(res,ms))
  ,   colors = ['orange', 'blue', 'green', 'pink', 'crimson', 'yellow']
  ;

document.querySelector('#button-loop').onclick = async ()=>
  {
  for (let color of colors)
    {
    document.body.style.backgroundColor = color
    await delay(1500)  // slow down colors changing
    }
  }
  
let colorId = -1
document.querySelector('#button-next').onclick = () =>
  {
  colorId = ++colorId % colors.length
  document.body.style.backgroundColor = colors[colorId]
  }
<button id="button-loop">color loop</button>
<button id="button-next">color next</button>

Upvotes: 0

54ka
54ka

Reputation: 3589

When performing the cycle, first put "black" then "blue" and so on. last put "yellow". Each placed element of colors array replaces the previous one, so you last see "yellow". If you want to get random color from your array tyr this:

let button = document.querySelector ('.button');
let background = document.querySelector ('body');
let colors = ['black', 'blue', 'green', 'white', 'brown', 'yellow'];

button.addEventListener ('click', function(){
    let r = Math.floor(Math.random() * colors.length) + 0;
    background.style.backgroundColor = colors[r];
});

Read more here: https://www.w3schools.com/js/js_random.asp

Upvotes: 0

Mechanic
Mechanic

Reputation: 5380

Why does 'for' loop only returns the last item in the array?

Because you tell it to do so. the for loop you are using inside the click listener will always run until it reaches the length of the array ( i < colours.length ), which means the latest element; I guess you instead try to change background on each click, and for is not a proper tool for that, you simply need some "index" that you increase every time it clicked, and reading the colour of that "index" from colours array;

let button = document.querySelector ('.button');
let background = document.querySelector ('body');
let colors = ['black', 'blue', 'green', 'white', 'brown', 'yellow'];
let colorIndex = 0;

button.addEventListener ('click', function(){
    background.style.backgroundColor = colors [colorIndex % colors.length];
    colorIndex++
})
<button class="button">change bg</button>

Upvotes: 1

You should put value of current index in closure, like this:

let button = document.querySelector ('.button');
let background = document.querySelector ('body');
let colors = ['black', 'blue', 'green', 'white', 'brown', 'yellow'];
let index = 0;

button.addEventListener ('click', function(){
    const _index = index++;
    background.style.backgroundColor = colors[_index];
    if (index === colors.length) {
        index = 0;
    }
})

Upvotes: 0

Naseh Badalov
Naseh Badalov

Reputation: 344

From what I understand you want to change the color of the element when it is clicked to the button. Your for loop will change the background when you click but it will happen very fast that you will not be able to see. With this code, you can change the color after every click by picking the next value in the colors array. Code:

let button = document.querySelector('.button');
let background = document.querySelector('body');
let colors = ['black', 'blue', 'green', 'white', 'brown', 'yellow'];
let cIndex = 0;

button.addEventListener('click', function () {
    background.style.backgroundColor = colors[cIndex];
    if (cIndex >= colors.length - 1) {
        cIndex = 0;
    } else {
        cIndex++;
    }
});

Explanation - First we create a cIndex variable to start from the beginning of the array. Then every time we click to the button cIndex gets incremented to get the next value in the array next time we click the button. Then we check if we reached the end of array with if statement. If we reached to the end of array we equal cIndex to zero to go back to the first value in the array.

Upvotes: 0

Related Questions