简体   繁体   English

在 javascript 中创建唯一值并推送到数组

[英]create unique value and push to array in javascript

I need to create a array with unique values.我需要创建一个具有唯一值的数组。 In here if the created value is include in that array, then need to create another value and again need to check that newly created value exists in that array, if again exists then need to do the same check.在这里,如果创建的值包含在该数组中,则需要创建另一个值并再次需要检查该数组中是否存在新创建的值,如果再次存在则需要进行相同的检查。

Here is the code I have tried, if I execute this, I think infinite looping scene happening.这是我尝试过的代码,如果我执行它,我认为会发生无限循环场景。

let arr = [];
for(let i=0; i<10;i++) {
  let k = 1;
  let pass = (Math.floor(Math.random() * (10 - 6 + 1)) + 6)+'a';
  while(k > 0){
    k++;
    if(arr.indexOf(pass) > -1) {
      pass = (Math.floor(Math.random() * (10 - 6 + 1)) + 6)+'a';
    } else {
      arr.push(pass);
      break;         
    }
   
    console.log(arr)
  }
}

What was the mistake in this code?这段代码有什么错误?

Yep, you're correct.是的,你是对的。 It's an infinite loop.这是一个无限循环。

The problem is the line pass = (Math.floor(Math.random() * (10 - 6 + 1)) + 6)+'a';问题是行pass = (Math.floor(Math.random() * (10 - 6 + 1)) + 6)+'a'; . . This will only ever generate one of 5 values.这只会生成 5 个值之一。 pass will only ever be pass将永远是

  • 6a 6a
  • 7a 7a
  • 8a 8a
  • 9a 9a
  • 10a 10a

Beause your array is 10 elements long, but you're only filling it with 5 possible elements, you will never be able to fill it with all unique elements.因为你的数组有 10 个元素长,但你只用 5 个可能的元素填充它,你永远无法用所有独特的元素填充它。 So it will go into an infinite loop trying to generate unique elements but never finding unique elements.所以它会 go 进入一个无限循环,试图生成唯一元素但永远找不到唯一元素。

You need to rewrite the calculation of pass to generate more than 5 unique elements.您需要重写 pass 的计算以生成 5 个以上的唯一元素。 Try pass = (Math.floor(Math.random() * 10))+'a';尝试pass = (Math.floor(Math.random() * 10))+'a'; and go from there.和 go 从那里。

 let arr = [(Math.floor(Math.random() * (10)))+'a']; for(let i=0; i<=10;i++) { let k = 0; let pass = (Math.floor(Math.random() * (10)))+'a'; while(k < arr.length){ k++; if(arr.indexOf(pass) > -1){ pass = (Math.floor(Math.random() * (10 - 6 + 1)) + 6)+'a'; }else { arr.push(pass); break; } } } console.log(arr)

variable k is always > 0 in your condition and it loops infinitely.在您的条件下,变量 k 始终 > 0 并且它无限循环。

edit 1:编辑1:

answer updated based on @Mathew answer答案基于@Mathew 答案更新

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

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