【问题标题】:function that takes an array and arguments separated by commas and returns a function that returns any number接受一个数组和用逗号分隔的参数并返回一个返回任意数字的函数的函数
【发布时间】: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


    【解决方案1】:

    如果没有数组交出,你可以取函数的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());

    【讨论】:

    • 它不起作用。 getRandomNumberTwo 也将是未定义的
    • 是的,在getRandomNumberTwo之后的示例代码中,console.log不正确
    • @ameli,对不起。现在它应该通过将arg 设置为数组来工作。原因是返回函数有一个自己的argument,而外部函数从未使用过。
    【解决方案2】:

    为此使用 rest 运算符。

    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)]
            }
        }
    };
    

    【讨论】:

    • ... 在函数参数列表上下文中使用时,称为rest 参数语法,而不是spread 语法
    • 它不适用于数组。输出为 const getRandomNumber = makeRandom([1, 2, 100, 34, 45, 556, 33]) console.log(getRandomNumber()) // [1, 2, 100, 34, 45, 556, 33] 控制台.log(getRandomNumber()) // [1, 2, 100, 34, 45, 556, 33] const getRandomNumberTwo = makeRandom(1, 2, 100, 34, 45, 556, 33) console.log(getRandomNumberTwo() ) // 2 console.log(getRandomNumberTwo()) //100
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    相关资源
    最近更新 更多