简体   繁体   English

如何从JS中的数组中删除特定字符?

[英]How to remove a specific character from array in JS?

How can I remove a special number from array in this example.在此示例中,如何从数组中删除特殊数字。 I have 9 numbers in array nums and empty array narr.我在数组 nums 和空数组 narr 中有 9 个数字。 I want to delete a random index (let rand) from nums and add this to narr.我想从 nums 中删除一个随机索引(让 rand)并将其添加到 narr。 In narr pushing is correct but when i tried delete the same number from nums by pop, splice, slice etc it didn't correct answer.在 narr 中,推送是正确的,但是当我尝试通过 pop、splice、slice 等从 nums 中删除相同的数字时,它没有正确答案。 Which metod should i use?我应该使用哪种方法?

function sudoku(arr){
  let nums = [1,2,3,4,5,6,7,8,9];
  let narr = [];
  for(let i = 0; i<9; i++){
    let rand = Math.floor(Math.random()*nums.length);
    narr.push(nums[rand]);
    nums.pop(nums[rand]);    
  }
  return narr; 
}

You should use splice() to remove the element from array.您应该使用splice()从数组中删除元素。 pop() removes last element. pop()删除最后一个元素。 If you want to remove an element from index rand you can use splice()如果要从索引rand删除元素,可以使用splice()

The first argument of splice() is the index from which you want to remove element and second argument is no of elements you want to remove splice()的第一个参数是要从中删除元素的索引,第二个参数是要删除的元素数

nums.splice(rand, 1);   

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

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