JavaScript函数生成对象的随机实例



我正在尝试创建一个由九个随机单词组成的数组。每个单词都应该有一个颜色键值。在九个单词中,3个单词应该有"红色"的颜色,3个单词应该有"蓝色"的颜色,一个单词shoule的颜色应该是"黑色"。颜色需要随机分配给单词(每次生成数组时,每种颜色的位置应随机变化(。

到目前为止,我的代码生成和单词数组,每个单词随机分配一种颜色,但没有限制 - 例如,我可能会得到 2 个黑色 3 个红色和 4 个蓝色。然后下次 0 黑色 4 红色和 5 蓝色。我每次需要产生 4 个红色 4 个蓝色和 1 个黑色(随机定位(。

我认为计数器会很有用,但目前尚未使用。

任何帮助都会很棒 - 我是编码新手,所以要挑剔!

这是我的代码:

//Globals
const wordList = [..... ***remov
ed giant list of words from post***
];
const colorList = ['red', 'blue', 'black']
let randomWordNum = Math.floor(Math.random()*(wordList.length))
let randomColorNum = Math.floor(Math.random()*(colorList.length))
let coloredWords = [];
let redCounter = 0;
let blueCounter = 0;
let blackCounter = 0;

//Square function
//assigns color and word value to object key
//pushes object to new array 'words'
const createSquare = () => {
let randomWordNum = Math.floor(Math.random()*(wordList.length))
let randomColor = colorList[Math.floor(Math.random()*(colorList.length))]
if (randomColor === 'red') {
redCounter++
} else if (randomColor === 'blue') {
blueCounter++
} else if (randomColor === 'black') {
blackCounter++
}
var square = {
color: randomColor,
word: wordList[randomWordNum],
}
coloredWords.push(square)
console.log(square)
}

//Loops through above function until the array is x values
const wordArr = () => {
while (coloredWords.length < 9 ){
createSquare()
}
}

wordArr()
console.log(coloredWords)

您可以先创建一个所有颜色的数组 3 次(例如['red', 'blue', 'black', 'red', 'blue', 'black', 'red', 'blue', 'black'](,然后对其进行洗牌,然后在每次迭代时,从数组中选择并删除一个元素:

//Globals
const wordList = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
const colorList = ['red', 'blue', 'black']
const coloredWords = [];
const COUNT_FOR_ONE_COLOR = 3;
const randomColorsArr = Array.from(
{ length: COUNT_FOR_ONE_COLOR * colorList.length },
(_, i) => colorList[i % colorList.length]
);
// Shuffle:
// https://stackoverflow.com/a/12646864
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
shuffleArray(randomColorsArr);
const createSquare = () => {
const randomWordNum = Math.floor(Math.random() * (wordList.length))
const randomColor = randomColorsArr.pop();
const square = {
color: randomColor,
word: wordList[randomWordNum],
}
coloredWords.push(square)
};
for (let i = 0; i < 9; i++) {
createSquare();
}
console.log(coloredWords)

最新更新