在关联数组查找中未定义

Undefined in associative array lookup

本文关键字:未定义 查找 数组 关联      更新时间:2023-09-26
var candidates = {           
  "1":"Barack Obama",
  "2":"Mitt Romney",
  "3":"Dennis Kucinich",
  "4":"Quentin Tarantino",
  "5":"Count Dracula"
};

    function getRandomInt(min, max){
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};
function getRandomPresident(){
  var num = getRandomInt(1, Object.size(candidates));
  if (num!=5){
    alert(num);
    var key = num.toString();
    var res = candidates[key];
    return res;

  } else {
        getRandomPresident();
  }
   }

 alert(getRandomPresident());

此代码有效,但有时在生成随机值后,它会输出"undefined"而不是名称 - http://jsbin.com/uriwal/edit#source 为什么?

重试(else块(时,不会返回新值。您应该通过以下方式传递返回值:

return getRandomPresident();

目前,您正在选取一个新项目,但由于函数不返回它,因此返回值为 undefined

我猜getRandomInt((函数可以返回0,而您的关联数组没有。只需在 if 子句中创建更严格的检查:

if (num >= 1 && num <= 5) {
    // do stuff
}

编辑:刮擦一下,你有getRandomInt(1,max(。无论如何,为什么还要有递归函数呢?只需这样做:

var num = 0;
while ((num = getRandomInt(1, ...)) > 5) {
    num = getRandomInt(1, ...);
}

返回资源希望这有帮助

将函数更改为:

function getRandomInt(min, max){
  return Math.floor(Math.random() * (max - min)) + min;
}