JS function - return an array of a range

There is such a JS programming question:

Write a js function, the function has an n (number type), its return value is an array, the array is n random and non-repeating integers, and the integer value range is [2,32]

First, define a function to return a range of values:

function getRand(a,b){
	var rand = Math.round(Math.random()*(b-a)+a);
	return rand;
}

Second, define a function to do the deduplication check:

function checkArrIn(rand,array){
    if(array.indexOf(rand) > -1){
        return true
    }
    return false;
}

Finally, the overall implementation:

function fn(n, min, max) {
	var arr = [];
	var isNum = !isNaN(Number(n));//Determine whether n is a number, including numbers of string type
	var isRandOk = (n >= min && n <= max && n <= (max - min)) ? true : false;//Determine whether the value of n meets the requirements
	if (n && isRandOk && isNum) {
		for (var i = 0; i < n; i++) {
			var rand = getRand (min, max);
			if (checkArrIn(rand, arr)) {
				i--
			} else {
				arr.push(rand)
			}
		}
	}
	return arr;
}


Points to note:

Math.round() rounds a number to the nearest integer

Math.ceil() rounds up a number

Math.floor() rounds down a number

references:

http://www.cnblogs.com/zhangxiaoshu/p/6515091.html



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325763987&siteId=291194637