3 回答

TA贡献1818条经验 获得超11个赞
您试图错误地访问数组,
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贡献1876条经验 获得超6个赞
我将帮助您了解现有代码以及其中的错误所在:
您不需要在这里获取 ids.indexOf(rand) ,原因是 Math.Random 将生成一个 0 到 1 之间的数字,然后将其与 ids.length 相乘。这意味着 Math.random() 的值将从 0 开始,可能达到 ids.length。因为您的数组也是从 0 开始的,所以您可以直接使用该值并将其作为参数传递到您将使用的函数中以拆分数组。
let rand = Math.floor(Math.random() * ids.length); let x = ids.indexOf(rand.toString());
Array.prototype.pop() 函数总是删除数组的最后一个元素并返回它的值。这就是为什么你总是得到最后一个元素的原因。
ids.pop(ids[x]);
您可以使用Array.prototype.splice()代替。这个函数的作用是,它接受 2 个参数 - 起始索引和结束索引,并且它会改变数组,这意味着它将改变你的原始数组。此外,它还会返回新数组中删除的元素的值。
我在下面添加了一个片段示例,您应该运行它并查看结果,最好将此代码复制到您自己的 IDE 并尝试使用 console.log( ) 来调试它以记录每一步的值看看发生了什么以获得更好的理解。请随意在这个问题下面的评论中提出任何疑问。
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贡献1815条经验 获得超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);
函数 splice() 从数组中的给定位置删除元素并将这些元素作为数组返回。
更多信息请参见: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
添加回答
举报