javascript - 返回未定义的随机对象数组
问题描述
我有这个随机数组函数,它应该从数组中选择一个范围,然后从随机选择的范围中随机选择,但它返回未定义的任何想法?我确实完美地拿起了文件。
function dynamicgenerator(array, name) {
//"name" is only for one array
let arrayPush = [];
try {
let arrayJson = require(`../json/${array}`)
//console.log(arrayJson)//returning true
for (i in arrayJson) {
arrayJson.push(arrayPush[`${i}`])
console.log(arrayPush)
let randomScope = Math.floor(Math.random() * arrayPush.length); //chooses a scope array out of arrayPush
let randomObject = Math.floor(Math.random() * randomScope.length);
let ret = randomScope[randomObject]
return ret;
}
} catch (e) {
console.log('DynamicGen returned err whether planned or not.')
let rand = Math.floor(Math.random() * name.length);
let ret = name[rand]
return ret;
}
}
解决方案
for
循环存在许多问题。但是这个循环是不必要的。它只是制作一个不必要的副本arrayJson
。- 分配时忘记索引数组
randomScope
。
function dynamicgenerator(array, name) {
try {
let arrayJson = require(`../json/${array}`)
let randomScope = arrayJson[Math.floor(Math.random() * arrayJson.length)]; //chooses a scope array out of arrayJson
let randomObject = Math.floor(Math.random() * randomScope.length);
let ret = randomScope[randomObject]
return ret;
} catch (e) {
console.log('DynamicGen returned err whether planned or not.')
let rand = Math.floor(Math.random() * name.length);
let ret = name[rand]
return ret;
}
}
推荐阅读
- postgresql - Postgres:根据会话变量自动填充“INSERT”字段
- python-3.x - 在 typing.NamedTuple 的子类中 member: str = 'test' 和 member = 'test' 有什么区别?
- javascript - 如何通过循环创建新变量(content_01、_02 等)
- javascript - 如何在 React Native 中刷新屏幕?
- python - “tensorflow_federated”没有属性“NamedTupleType”
- konvajs - 使用 React Konva 添加填充
- sql - 如何对sql中的列求和
- typescript - 如何使用静态和动态键为对象定义 TypeScript 类型?
- php - laravel 传递控制器对象而不是类
- python - 如何避免在 Python for 循环中截断我的 CSV 输出?