我正在编写一个脚本,我必须从数组中随机生成一个数字,然后删除该数字,以便不能再次生成它。似乎正在发生的事情是,在拼接之后生成的数字正在从我的阵列中删除其他数字。我认为它正在减去。这是必要的代码:
var randNum = [0,1,2,3,4,5,6,7,8,9];
function clickHandler ()
{
output = randNum[Math.floor(Math.random() * randNum.length)];
console.log("This is the generated number:" + output);
randNum.splice(output);
console.log("This is the resulting array without the generated number:" + randNum);
}
答案 0 :(得分:4)
你混淆了价值和指数。
Array#splice
需要计算拼接元素。如果未提供,splice
将给定索引中的所有项目拼接到结尾。
var randNum = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
function clickHandler() {
var index = Math.floor(Math.random() * randNum.length);
console.log("This is the generated number: " + randNum[index]);
randNum.splice(index, 1);
console.log("This is the resulting array without the generated number: " + randNum);
}
clickHandler();
clickHandler();

答案 1 :(得分:1)
使用randNum.splice(index, 1);
仅从数组中删除一个数字
如果省略deleteCount
,或者它的值大于array.length - start(即,如果它大于数组中剩余的元素数,从start开始),则全部从数组开始到结束的元素将被删除
答案 2 :(得分:0)
这是另一种方法。
let numbersLeft = [0,1,2,3,4,5,6,7,8,9];
let numbersPulled = [];
function generateNumber(){
let randomNumber = randNum[Math.floor(Math.random() * randNum.length)];
return randomNumber;
}
function clickHandler () {
let numberToPull = generateNumber();
if ( numbersPulled.indexOf(numberToPull) != -1){
numbersLeft.splice(numberToTest, 0);
numbersPulled.push(numberToTest);
} else {
console.log('That number has already been pulled!');
}
}