首页 > 解决方案 > 接受一个数组和用逗号分隔的参数并返回一个返回任意数字的函数的函数

问题描述

请帮忙。我需要编写一个函数,该函数接受一个数字数组并返回一个函数,该函数在调用时会返回传递给它的该数组中的任何数字,而且,您不仅可以通过数组传递范围,还可以将参数作为分隔的参数传递用逗号。

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

使用数组它可以工作,但使用参数它会产生未定义的

标签: javascriptarrays

解决方案


arguments如果没有移交数组,您可以使用该功能。

function makeRandom(arg) {
    if (arg.constructor !== Array) {
        arg = Array.from(arguments);
    }
    return function() {
        return arg[Math.floor(Math.random() * arg.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());
console.log(getRandomNumberTwo());


推荐阅读