最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript color Array - Stack Overflow

programmeradmin4浏览0评论

I watched a codecademy video and have been unable to randomize my color array. The colors are not random. I am not sure what I am doing wrong.

    function getRandomColor() {
    var color;
    var colorArray = [
        "#FF6633",
        "#FFB399",
        "#FF33FF",
        "#FFFF99",
        "#00B3E6",
        "#E6B333",
        "#3366E6",
        "#999966",
        "#809980",
        "#E6FF80",
        "#1AFF33",
        "#999933",
        "#FF3380",
        "#CCCC00",
        "#66E64D",
        "#4D80CC",
        "#FF4D4D",
        "#99E6E6",
        "#6666FF"
    ];
    for (var i = 0; i < colorArray; i++) {
        color = colorArray[Math.floor(Math.random() * colorArray.length)];
    }
    return color;
}

I watched a codecademy video and have been unable to randomize my color array. The colors are not random. I am not sure what I am doing wrong.

    function getRandomColor() {
    var color;
    var colorArray = [
        "#FF6633",
        "#FFB399",
        "#FF33FF",
        "#FFFF99",
        "#00B3E6",
        "#E6B333",
        "#3366E6",
        "#999966",
        "#809980",
        "#E6FF80",
        "#1AFF33",
        "#999933",
        "#FF3380",
        "#CCCC00",
        "#66E64D",
        "#4D80CC",
        "#FF4D4D",
        "#99E6E6",
        "#6666FF"
    ];
    for (var i = 0; i < colorArray; i++) {
        color = colorArray[Math.floor(Math.random() * colorArray.length)];
    }
    return color;
}
Share Improve this question edited Feb 23, 2020 at 12:08 Alon Eitan 12k8 gold badges51 silver badges60 bronze badges asked Feb 23, 2020 at 11:47 cs.studentcs.student 291 silver badge3 bronze badges 2
  • 2 Does this answer your question? How to randomize (shuffle) a JavaScript array? – Alon Eitan Commented Feb 23, 2020 at 11:50
  • Can you clarify what you mean by randomizing your color array? Right now your code iterates over all colors and then returns the last one that was randomly selected. – jSebestyén Commented Feb 23, 2020 at 12:10
Add a ment  | 

6 Answers 6

Reset to default 6

I don't know why you need the for loop but I am quite sure that it is wrong.

What is the problem?

In your case, the loop won't be executed because colorArray(in the condition) is not a number. You may wanted to use colorArray.length instead but there is no point for the loop in that case too.

select one random color

If you just want to select one color, you can just replace the whole loop (and the return statement) with:

return colorArray[Math.floor(Math.random() * colorArray.length)];

This will just return a random color.

shuffle it

If you want to shuffle the whole array, you could use the following loop:

for (var i = 0; i < colorArray.length; i++) {
    let r=Math.floor(Math.random() * colorArray.length);
    color = colorArray[r];
    colorArray[r]=colorArray[i];
    colorArray[i]=color;
}

add length to your loop for (var i = 0; i < colorArray.length; i++)

function getRandomColor() {
    var color;
    var colorArray = [
       "#FF6633",
       "#FFB399",
       "#FF33FF",
       "#FFFF99",
       "#00B3E6",
       "#E6B333",
       "#3366E6",
       "#999966",
       "#809980",
       "#E6FF80",
       "#1AFF33",
       "#999933",
       "#FF3380",
       "#CCCC00",
       "#66E64D",
       "#4D80CC",
       "#FF4D4D",
       "#99E6E6",
       "#6666FF"
    ];
    for (var i = 0; i < colorArray.length; i++) {
       color = colorArray[Math.floor(Math.random() * colorArray.length)];
    }
    return color;
}

I think you forgot to put the ".length" on your for loop. for(var i = 0; i < colorArray.length; i++)

If you want to shuffle the array you can use the following function:

var colorArray = ["#FF6633", "#FFB399", "#FF33FF", "#FFFF99", "#00B3E6", "#E6B333", "#3366E6", "#999966", "#809980", "#E6FF80", "#1AFF33", "#999933", "#FF3380", "#CCCC00", "#66E64D", "#4D80CC", "#FF4D4D", "#99E6E6", "#6666FF"];

function shuffleArray() {
  colorArray.sort(function() {
    return Math.random() - 0.5;
  });
}

shuffleArray();
console.log(colorArray);

If you just want to get a random item you can do:

var colorArray = ["#FF6633", "#FFB399", "#FF33FF", "#FFFF99", "#00B3E6", "#E6B333", "#3366E6", "#999966", "#809980", "#E6FF80", "#1AFF33", "#999933", "#FF3380", "#CCCC00", "#66E64D", "#4D80CC", "#FF4D4D", "#99E6E6", "#6666FF"];

function getRandomColor() {
  return colorArray[Math.random() * colorArray.length | 0];
}

console.log(getRandomColor());

You can just create a function which randomise.

function randomizeArr () {
   const randomLength=Math.floor(Math.random() * colorArr.length);
   return colorArr[randomLength];
}

And in your for-loop your condition is wrong it should have been i < colorArr.length instead of colorArr.

Generally arr.length is a property it not a method like map() or reduce() etc.

Hope my answer is clear!

This program produces a random background color by pressing a button. The colors are "X11 colors" from the CSS3 specification WebColors. I manually loaded these colors to the array, which is hopefully useful information for somebody. Of course, you can probably create the same array by doing a webscrape has anybody done this.

const btn = document.querySelector('button');

var items = ['MediumVioletRed', 'DeepPink', 'PaleVioletRed', 'HotPink', 
   'LightPink', 'Pink', 'DarkRed', 'Red', 'Firebrick', 'Crimson', 
   'IndianRed', 'LightCoral', 'Salmon', 'DarkSalmon', 
   'LightSalmon', 'OrangeRed', 'Tomato', 'DarkOrange', 'Coral', 
   'Orange', 'DarkKhaki', 'Gold', 'Khaki', 'PeachPuff', 'Yellow', 
   'PaleGoldenrod', 'Moccasin', 'PapayaWhip', 'LightGoldenrodYellow', 
   'LemonChiffon', 'LightYellow','Maroon', 'Brown', 'SaddleBrown', 'Sienna', 
   'Chocolate', 'DarkGoldenrod', 'Peru', 'RosyBrown', 'Goldenrod', 
   'SandyBrown', 'Tan', 'Burlywood', 'Wheat', 'NavajoWhite', 'Bisque', 
   'BlanchedAlmond', 'Cornsilk','DarkGreen', 'Green', 'DarkOliveGreen', 
   'ForestGreen', 'SeaGreen', 'Olive', 'OliveDrab', 'MediumSeaGreen', 
   'LimeGreen', 'Lime', 'SpringGreen', 'MediumSpringGreen', 'DarkSeaGreen', 
   'MediumAquamarine', 'YellowGreen', 'LawnGreen', 'Chartreuse', 'LightGreen', 
   'GreenYellow', 'PaleGreen', 'Teal', 'DarkCyan', 'LightSeaGreen', 
   'CadelBlue', 'DarkTurquoise', 'MediumTurquoise', 'Turquoise', 'Aqua', 
   'Cyan', 'AquaMarine', 'PaleTurquoise', 'LightCyan', 'Navy', 'DarkBlue', 
   'MediumBlue', 'Blue', 'MidnightBlue', 'RoyalBlue', 'SteelBlue', 
   'DodgerBlue', 'DeepSkyBlue', 'CornFlowerBlue', 'SkyBlue', 'LightSkyBlue', 
   'LightSteelBlue', 'LightBlue', 'PowderBlue', 'Indigo', 'Purple', 
   'DarkMagenta', 'DarkViolet', 'DarkSlateBlue', 'BlueViolet', 'DarkOrchid', 
   'Fuchsia', 'Magenta', 'SlateBlue', 'MediumSlateBlue', 
   'MediumOrchid', 'MediumPurple', 'Orchid', 'Violet', 'Plum', 
   'Thistle', 'Lavender', 'MistyRose', 'AntiqueWhite', 'Linen', 
   'Beige', 'WhiteSmoke', 'LavenderBlush', 'OldLace', 'AliceBlue', 
   'Seashell', 'GhostWhite', 'Honeydew', 'ForalWhite', 'Azure', 
   'MintCream', 'Snow', 'Ivory', 'White', 'Black', 'DarkSlateGray', 
   'DimGray', 'SlateGrey', 'Gray', 'LightSlateGray', 'DarkGray', 
   'Silver', 'LightGray', 'Gainsboro'];

function random_item(items)
{
  
    return items[Math.floor(Math.random()*items.length)];
     
}



btn.addEventListener('click', () => {
   const rndWebCol = (random_item(items));

   document.body.style.backgroundColor = rndWebCol;
  
   console.log(rndWebCol);
  
});
发布评论

评论列表(0)

  1. 暂无评论