ForeveHG / Frontend-Daily-Interview

学习,尝试回答一些前端面试题
1 stars 0 forks source link

66. 用递归算法实现,数组长度为5且元素的随机数在2-32间不重复的值 #67

Open ForeveHG opened 3 years ago

ForeveHG commented 3 years ago

题目来源:https://github.com/haizlin/fe-interview/issues/3

ForeveHG commented 3 years ago
  1. 2-32间的随机数
    Math.random() * 30 + 2
  2. 递归
    function buildNum(len, arr=[]) {
    if(arr.length < len) {
        const num = parseInt(Math.random() * 30 + 2);
        if(arr.indexOf(num) == -1 ) arr.push(num)
        buildNum(len, arr)
    }
    return arr
    }
  3. 调用
    buildNum(5); //[3, 12, 18, 7, 20]