gpt4 book ai didi

jquery - 使用 jQuery 每 4 秒显示 3 种随机颜色

转载 作者:行者123 更新时间:2023-12-01 03:30:36 24 4
gpt4 key购买 nike

我有这段代码,我试图每 4 秒一次从数组中显示 3 种随机颜色,但我每 4 秒得到 1 种颜色,即使它们是正确的随机...

我错过了什么?

//set colors
var colors = ["white", "red", "blue", "yellow", "orange", "brown", "black", "violet", "purple", "pink", "green"];

//pick 3 of them randomly
var three_random_colors = (n) => {
return colors.reduce((memo, val, index) => {
var p = (n-memo.length); // How many remaining to choose.
var q = colors.length-index; // How many remaining to choose from.
if (Math.random() < p/q){
memo.push(val);
}
return memo;
}, []);
};

//output the colors on the HTML
var counter = 0; //start counter
var elem = document.getElementById("changeText");//the place where we change things
setInterval(change, 4000);//every 4 seconds run the following stuff:
function change() {
var text = three_random_colors(3);//get what's inside "three_random_colors"
elem.innerHTML = text[counter];//on div, add content <--- (I want 3 at once here! but I get only 1)
counter++;
if(counter >= text.length) { counter = 0; var text = three_random_colors(3); }//reset
}

最佳答案

您的问题是您的 change 函数一次仅输出一种颜色。您可以将其简化为仅输出(例如)

text.join(' ')

您将看到所有三种颜色:

//set colors
var colors = ["white", "red", "blue", "yellow", "orange", "brown", "black", "violet", "purple", "pink", "green"];

//pick 3 of them randomly
var three_random_colors = (n) => {
return colors.reduce((memo, val, index) => {
var p = (n - memo.length); // How many remaining to choose.
var q = colors.length - index; // How many remaining to choose from.
if (Math.random() < p / q) {
memo.push(val);
}
return memo;
}, []);
};

//output the colors on the HTML
var elem = document.getElementById("changeText"); //the place where we change things
setInterval(change, 4000); //every 4 seconds run the following stuff:
function change() {
var text = three_random_colors(3); //get what's inside "three_random_colors"
elem.innerHTML = text.join(' '); //on div, add content <--- (I want 3 at once here! but I get only 1)
}
<div id="changeText"></div>

关于jquery - 使用 jQuery 每 4 秒显示 3 种随机颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60244721/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com