首页 > 解决方案 > 返回未定义的随机对象数组

问题描述

我有这个随机数组函数,它应该从数组中选择一个范围,然后从随机选择的范围中随机选择,但它返回未定义的任何想法?我确实完美地拿起了文件。

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;

  }
}

标签: javascriptarraysloopsobject

解决方案


  1. for循环存在许多问题。但是这个循环是不必要的。它只是制作一个不必要的副本arrayJson
  2. 分配时忘记索引数组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;
  }
}


推荐阅读