How to randomly generate numbers without repetition in javascript?

前端 未结 11 2390
时光取名叫无心
时光取名叫无心 2020-12-06 11:52

I want to generate each number between 0 to 4 randomly using javascript and each number can appear only once. So I wrote the code:

for(var l=0; l<5; l++)          


        
11条回答
  •  南方客
    南方客 (楼主)
    2020-12-06 12:48

    function getRanArr(lngth) {
      let arr = [];
      do {
          let ran = Math.floor(Math.random() * lngth); 
          arr = arr.indexOf(ran) > -1 ? arr : arr.concat(ran);
       }while (arr.length < lngth)
       
       return arr;
    }
    
    const res = getRanArr(5);
    
    console.log(res);

提交回复
热议问题