[DataContract]
我想将colors数组中的3种随机颜色推送到randomColors中。 我不希望任何颜色重复。
看起来很简单,但是我花了几个小时不能让它不重复。谢谢!
答案 0 :(得分:0)
您可以使用以下内容:
let colors = ['blue','red','orange','purple','gray','yellow'];
let randomColors = [];
// log our initial output
console.log ( "colors: " + colors );
console.log ( "randomColors: " + randomColors );
// this is the loop that pulls colors out of the colors array at random and assigns them to the randomColors array
// this function is destructive on the colors array, so copy it first if you want to keep the array intact
// The iterations var can be changed to however many you like, but it will fail if you specify a number larger
// than there are colors in the array
var iterations = 3;
for ( var i = 0; i < iterations; i++ ) {
// grab a random color from the initial array
var item = colors[Math.floor(Math.random()*colors.length)];
var idx = colors.indexOf(item);
// add it to the randomColors array
randomColors[i] = item;
// remove it from the colors array so it isn't picked again
colors.splice(idx, 1);
}
// log our resultant output for comparison
console.log ( "colors: " + colors );
console.log ( "randomColors: " + randomColors );
答案 1 :(得分:0)
let excludedIndexes = [];
let currentIndex = null;
let colors = ['blue','red','orange','purple','gray','yellow'];
let randomColors = [];
function getNextRandom(max)
{
return Math.floor(Math.random()*max);
}
function addColors(numColors)
{
let i = 0;
randomColors = [];
excludedIndexes = [];
while(i < numColors)
{
currentIndex = getNextRandom(colors.length);
while(excludedIndexes.indexOf(currentIndex)!=-1)
{
currentIndex = getNextRandom(colors.length);
}
randomColors.push(colors[currentIndex]);
excludedIndexes.push(currentIndex);
i++;
}
}
addColors(3);//modifies the randomColors array each time it's called
在浏览器控制台中测试。
不得不修复几行,但现在应该可以正常工作了。
答案 2 :(得分:0)
最简单的方法是在 lodash 包中使用shuffle
功能。 https://lodash.com/docs#shuffle
然后从随机数组中选择所需的颜色数:
const colors = ['blue','red','orange','purple','gray','yellow'];
const selectedColors = _.shuffle(colors).splice(0, 3); // 3 random colors
console.log(selectedColors);
答案 3 :(得分:0)
也许是一个笨拙的工具
function random_num_between(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
}
function pick_one(list){
const index = random_num_between(0,list.length-1)
return list[index]
}
function get_elements_distinct(originList,num){
const map = {}
let counter = 0
while(counter < num){
const key = pick_one(originList)
if(map[key] == null){
counter ++
map[key] = 1
}
}
return Object.keys(map)
}
然后你可以使用它
let colors = ['blue','red','orange','purple','gray','yellow']
let randomColors = get_elements_distinct(colors,3);