簡體   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