dimanche 1 décembre 2019

Javascript Assigning a new variable inside an array while looping

//I am trying to make every element in the array colors get assigned a different color, but when I run this some elements are changed to the color name and some aren't, also could a switch be better for this, if so how?

colors = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];  

function randomColor() {  //fills the array with a number from 1 - 16
  for (let i of colors) {
    colors[i] = Math.floor(Math.random()*15+1);
    if (colors[i] === 1) {
    colors[i] = "red";
    }   
    else if (colors[i] === 2){
        colors[i] = "blue";}
    else if (colors[i] === 3){
        colors[i] = "yellow";}
    else if (colors[i] === 4){
        colors[i] = "orange";}
    else if (colors[i] === 5){
        colors[i] = "purple";}
    else if (colors[i] === 6){
        colors[i] = "pink";}
    else if (colors[i] === 7){
        colors[i] = "green";}
    else if (colors[i] === 8){
        colors[i] = "gray";}
    else if (colors[i] === 9){
        colors[i] = "black";}
    else if (colors[i] === 10){
        colors[i] = "white";}
    else if (colors[i] === 11){
        colors[i] = "darkblue";}
    else if (colors[i] === 12){
        colors[i] = "darkgreen";}
    else if (colors[i] === 13){
        colors[i] = "darkyellow";}
    else if (colors[i] === 14){
        colors[i] = "darkpurple";}
    else if (colors[i] === 15){
        colors[i] = "lightgreen";}
    else if (colors[i] === 16){
        colors[i] = "lightblue";}
    else { colors[i] === "clear";}
  }
    colors[0] = Math.floor(Math.random()*15+1);

    return colors;
}


randomColors();



Aucun commentaire:

Enregistrer un commentaire