3 回答

TA貢獻(xiàn)1818條經(jīng)驗 獲得超11個贊
您試圖錯誤地訪問數(shù)組,
function idHandler() {
let rand = Math.floor(Math.random() * ids.length);
let x = ids[rand]
ids.splice(rand,1) // can use this to remove an index from array
cards[rand].setAttribute("id", x); // values should already be strings as they are stored with "" marks
}
如果您不需要x再次使用該變量,實際上可以跳過一個步驟
function idHandler() {
let rand = Math.floor(Math.random() * ids.length);
cards[rand].setAttribute("id", ids[rand]); // values should already be strings as they are stored with "" marks
ids.splice(rand,1) // can use this to remove an index from array
}

TA貢獻(xiàn)1876條經(jīng)驗 獲得超6個贊
我將幫助您了解現(xiàn)有代碼以及其中的錯誤所在:
您不需要在這里獲取 ids.indexOf(rand) ,原因是 Math.Random 將生成一個 0 到 1 之間的數(shù)字,然后將其與 ids.length 相乘。這意味著 Math.random() 的值將從 0 開始,可能達(dá)到 ids.length。因為您的數(shù)組也是從 0 開始的,所以您可以直接使用該值并將其作為參數(shù)傳遞到您將使用的函數(shù)中以拆分?jǐn)?shù)組。
let rand = Math.floor(Math.random() * ids.length); let x = ids.indexOf(rand.toString());
Array.prototype.pop() 函數(shù)總是刪除數(shù)組的最后一個元素并返回它的值。這就是為什么你總是得到最后一個元素的原因。
ids.pop(ids[x]);
您可以使用Array.prototype.splice()代替。這個函數(shù)的作用是,它接受 2 個參數(shù) - 起始索引和結(jié)束索引,并且它會改變數(shù)組,這意味著它將改變你的原始數(shù)組。此外,它還會返回新數(shù)組中刪除的元素的值。
我在下面添加了一個片段示例,您應(yīng)該運(yùn)行它并查看結(jié)果,最好將此代碼復(fù)制到您自己的 IDE 并嘗試使用 console.log( ) 來調(diào)試它以記錄每一步的值看看發(fā)生了什么以獲得更好的理解。請隨意在這個問題下面的評論中提出任何疑問。
let ids = ["1", "1", "2", "2", "3", "3", "4", "4", "5", "5", "6", "6"];
function idHandler() {
const rand = Math.floor(Math.random() * ids.length);
const x = ids.splice(rand, 1)[0];
//[0] in above line to return the removed element instead of an array
//containing the element
console.log(x);
console.log(ids);
}
idHandler();

TA貢獻(xiàn)1815條經(jīng)驗 獲得超13個贊
我想你想要的是splice這樣的:
const cards = document.querySelectorAll(".memory-card");
let ids = ["1", "1", "2", "2", "3", "3", "4", "4", "5", "5", "6", "6"];
function idHandler() {
let rand = Math.floor(Math.random() * ids.length);
let x = ids.indexOf(rand.toString());
var removedIds = ids.splice(ids[x], 1);
cards[x].setAttribute("id", removedIds[0]);
}
cards.forEach(mapIds);
函數(shù) splice() 從數(shù)組中的給定位置刪除元素并將這些元素作為數(shù)組返回。
更多信息請參見: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
添加回答
舉報