为什么我的函数(被调用时)总是以未定义的形式返回?

时间:2018-03-04 08:45:55

标签: javascript html

我已经为我正在设计的基于网络的游戏编写了一个函数,但每当我调用此函数时,它都会返回undefined。

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

function getOttomanRival() {
  return this.getRnd(1, 3)
  if (ottoman.rival == 1) {
    var ottoman.rival = "Mamluks"
  }
  if (ottoman.rival == 2) {
    var ottoman.rival = "Delhi"
  }
  if (ottoman.rival == 3) {
    var ottoman.rival = "Timurids"
  }

  function myFunction() {
    var ottoman = {
      rival: getOttomanRival()
    }
    document.GetElementById("ottomanRival").innerHTML = ottoman.rival()
  }
}
<button onclick="myFunction()">Click me</button>
<p id="ottomanRival"></p>

1 个答案:

答案 0 :(得分:1)

//This function (get Rand) looks good
function getRnd(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getOttomanRival() {
  return this.getRnd(1, 3) // if you return from here, none of the 
                           // following sentences will be executed
                           // Also you expect the rival name to be returned
                           // So store the random number in a variable
                           // and use it in your if condition and return
                           // the rival name once its set.
                           // Also "this" is not required here

  if (ottoman.rival == 1) { // check the random number generated,
                            // not the rival name against 1
    var ottoman.rival = "Mamluks"; // there is no syntax that declares
                                   // a variable "ottoman.rival" "." is 
                                   // not a valid variable name
                                   // use a simple variable
                                   // This function doesn't even need to know about
                                   // the structure of final object
  }
  if (ottoman.rival == 2) {
    var ottoman.rival = "Delhi"
  }
  if (ottoman.rival == 3) {
    var ottoman.rival = "Timurids"
  } 

  // missing a closing } for getOttomanRival

  function myFunction() {
    var ottoman = {
      rival: getOttomanRival()
    }
    document.GetElementById("ottomanRival").innerHTML = ottoman.rival() 
       // you probably meant "ottoman.rival"
       // without "()" as rival holds the result of `getOttomanRival()"
       // which is a string and not a function
  }
}

&#13;
&#13;
function getRnd(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getOttomanRival() {
  var x = getRnd(1, 3),
    rival;
  if (x == 1) {
    rival = "Mamluks"
  }
  if (x == 2) {
    rival = "Delhi"
  }
  if (x == 3) {
    rival = "Timurids"
  }
  return rival;
}

function myFunction() {
  var ottoman = {
    rival: getOttomanRival()
  };
  document.getElementById("ottomanRival").innerHTML = ottoman.rival;
}
&#13;
<button onclick="myFunction()">Click me</button>
<p id="ottomanRival"></p>
&#13;
&#13;
&#13;