繁体   English   中英

如何在递归之前从数组中删除某个元素?

[英]How do I remove a certain element from my array just before the recursion?

So I'm trying to make a basic bomb wire cutting game where you get 4 randomly picked colors from an array of 6 possible colors, but I'm having trouble with getting it so there are no duplicate colors in the 4 random colors. 我不确定如何从阵列中删除已经选择的 colors。 我认为我的逻辑是错误的。

const colors = ['Blue', 'Red', 'Yellow', 'White', 'Black', 'Green']
function getXRandomColors(colors, x, result) {
    if (x === 0) return result
    const randomIndex = Math.floor(Math.random() * colors.length)
    if (colors.includes(randomIndex)){
        colors = colors.filter(color => color !== randomIndex)}
    return getXRandomColors(colors, x - 1, [...result, colors[randomIndex]])
}
var fourRandomColors = getXRandomColors(colors, 4, [])
console.log('The wires are: ' + fourRandomColors);

我会创建一个临时变量设置为选择的颜色,然后在继续递归之前在randomIndex删除该数组条目。

const colors = ['Blue', 'Red', 'Yellow', 'White', 'Black', 'Green']
function getXRandomColors(colors, x, result) {
    if (x === 0) return result
    const randomIndex = Math.floor(Math.random() * colors.length)
    let pickedColor = colors[randomIndex];
    colors.splice(randomIndex, 1);
    return getXRandomColors(colors, x - 1, [...result, pickedColor])
}
var fourRandomColors = getXRandomColors(colors, 4, [])
console.log('The wires are: ' + fourRandomColors);

这样你就可以保证不会有任何重复。

在您当前的示例中出现了几个问题:

在你的过滤器 function

    colors = colors.filter(color => color !== randomIndex)}

条件( color !== randomIndex )将始终为真,因为随机索引是一个数字,而颜色是一个字符串。 如果您比较索引,您想要做的是;

    colors = colors.filter((color, index) => index !== randomIndex)}

但即使这样也不会得到想要的结果,因为您要从数组中删除随机索引而不将其存储在某处,这就是重复项首先出现的方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM