【发布时间】:2020-08-01 15:21:03
【问题描述】:
请帮忙。我需要编写一个函数,该函数接受一个数字数组并返回一个函数,该函数在调用时会返回传递给它的该数组中的任何数字,而且,您不仅可以通过数组传递范围,还可以将参数作为分隔的参数传递用逗号。
function makeRandom(arg) {
if(arg.constructor === Array) {
return function() {
return arg[Math.floor(Math.random() * arg.length)]
}
} else {
return function() {
let args = Array(arg);
return args[Math.floor(Math.random() * args.length)]
}
}
};
const getRandomNumber = makeRandom([1, 2, 100, 34, 45, 556, 33])
console.log(getRandomNumber()) // 556
console.log(getRandomNumber()) // 100
const getRandomNumberTwo = makeRandom(1, 2, 100, 34, 45, 556, 33)
console.log(getRandomNumberTwo()) // undefined
console.log(getRandomNumberTwo()) // undefined
使用数组它可以工作,但使用参数它会产生未定义
【问题讨论】:
标签: javascript arrays