简体   繁体   English

Javascript:调用函数从函数内返回一个值?

[英]Javascript: call a function to return a value from within a function?

Bit complicated to phrase but I have one function that needs to call another one to get a value returned to use in the first function - an example: 有点复杂到短语,但我有一个函数需要调用另一个函数来获取返回在第一个函数中使用的值 - 例如:

The first function needs to get the variable gameTitle from the function getGameInfo() 第一个函数需要从函数getGameInfo()获取变量gameTitle

function getGameInfo(){
     var gameTitle = "test game";

    if(gameTitle){
        return gameTitle;
    }else{
        return undefined;
    };

};

function getImages(){

    var gameTitle = getGameInfo();
     console.log(getGameInfo());

};

but for some reason this never works - it always returns "undefined" - I am extremely confused why this is happening 但由于某种原因,它永远不会起作用 - 它总是返回“未定义” - 我非常困惑为什么会发生这种情况

EDIT: I was given an answer in the comments by Pointy - this was not my whole code as this was an example but I was using an asynchronous API and was trying to get the function to return a value from an callback hence the issue of undefined!!! 编辑:我在Pointy的评论中得到了答案 - 这不是我的整个代码,因为这是一个例子,但我使用的是异步API,并试图让函数从回调中返回一个值,因此问题是undefined !

getValue returns correctly, so I assume your problem is that testFunction returns undefined . getValue正确返回,所以我假设你的问题是testFunction返回undefined It is because you didn't specify it what to return, you only told it to print something on the console. 这是因为你没有指定它返回什么,你只告诉它在控制台上打印一些东西。 If you also want it to return something, add a return statement to it. 如果您还希望它返回一些内容,请为其添加一个return语句。

function testFunction(){

  var newValue = getValue();
  console.log(newValue);
  return newValue;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM