简体   繁体   English

从数组中删除数字-Javascript

[英]Removing Numbers From An Array - Javascript

I am writing a script where I have to randomly generate a number from an array and then remove the number so that it cannot be generated again. 我正在编写一个脚本,在该脚本中,我必须从数组中随机生成一个数字,然后删除该数字,以使其无法再次生成。 What appears to be happening is that the number generated, after being spliced, is removing other numbers from my array. 似乎正在发生的事情是,生成的数字在拼接后正在从我的数组中删除其他数字。 I assume it is being subtracted. 我认为它正在被减去。 Here is the necessary code: 这是必要的代码:

    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);


        }

You mix up value and index. 您将值和索引混合在一起。

Array#splice needs a count for splicing elements. Array#splice需要一个用于拼接元素的计数。 If not supplied, splice splices all items from the given index to the end. 如果未提供,则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(); 

Use randNum.splice(index, 1); 使用randNum.splice(index, 1); to remove only one number from array 从数组中只删除一个数字

If deleteCount is omitted, or if its value is larger than array.length - start (that is, if it is greater than the number of elements left in the array, starting at start), then all of the elements from start through the end of the array will be deleted 如果省略deleteCount ,或者其值大于array.length-开始(即,如果大于数组中剩余的元素数量,则从start开始),则所有元素均从start到end的阵列将被删除

MDN MDN

This is another way of doing it. 这是另一种方式。

    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!');
      }
    }

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

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