javascript - 接受一个数组和用逗号分隔的参数并返回一个返回任意数字的函数的函数
问题描述
请帮忙。我需要编写一个函数,该函数接受一个数字数组并返回一个函数,该函数在调用时会返回传递给它的该数组中的任何数字,而且,您不仅可以通过数组传递范围,还可以将参数作为分隔的参数传递用逗号。
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
使用数组它可以工作,但使用参数它会产生未定义的
解决方案
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());
推荐阅读
- reactjs - 无效的挂钩调用。钩子只能在函数组件的主体内部调用。请救我脱离疯狂
- hadoop - 使用 hadoop 库在 YARN 上等待日志聚合
- javascript - 使用 Google 身份验证重定向时卡住
- vb.net - vb.net 循环遍历选定的项目列表框
- debugging - tct 命令在后台是如何工作的?
- swiftui - SwiftUI - 如何在视图上拖动和释放时获得通知
- flutter - 如何在 Flutter 应用中设置前台通知?
- c - 在 c 中使用 malloc 时的自由变量
- javascript - 使用 aframe 在 VR 中动态设置子弹模板的旋转
- javascript - Node.js 如何根据 SQL 查询结果发送 http 响应(在回调中处理异常)