如何在 Javascript 的另一个函数中使用返回值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19674992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:26:38  来源:igfitidea点击:

How to use a return value in another function in Javascript?

javascript

提问by GeekByDesign

I'm self-teaching myself JavaScript and out of curiosity I'm wondering what is the proper way of returning a value from one function to be used in another function. For example:

我正在自学 JavaScript,出于好奇,我想知道从一个函数返回值以在另一个函数中使用的正确方法是什么。例如:

function firstFunction() {
  // do something;
  return somevalue 
}

So how do I set up the second function to use somevalue? Thanks.

那么如何设置第二个函数来使用某个值呢?谢谢。

回答by Hanky Panky

Call the function and save the return value of that very call.

调用该函数并保存该调用的返回值。

function firstFunction() {
  // do something
  return "testing 123";
}

var test = firstFunction();  // this will grab you the return value from firstFunction();
alert(test);

You can make this call from another function too, as long as both functions have same scope.

您也可以从另一个函数进行此调用,只要这两个函数具有相同的scope

For example:

例如:

function testCase() {
  var test = firstFunction(); 
  alert(test);
}

Demo

演示

回答by leaf

You could call firstFunctionfrom secondFunction:

您可以firstFunctionsecondFunction以下位置致电:

function secondFunction() {
    alert(firstFunction());
}

Or use a global variable to host the result of firstFunction:

或者使用全局变量来承载以下结果firstFunction

var v = firstFunction();
function secondFunction() { alert(v); }

Or pass the result of firstFunctionas a parameter to secondFunction:

或者将结果firstFunction作为参数传递给secondFunction

function secondFunction(v) { alert(v); }
secondFunction(firstFunction());

Or pass firstFunctionas a parameter to secondFunction:

或者firstFunction作为参数传递给secondFunction

function secondFunction(fn) { alert(fn()); }
secondFunction(firstFunction);

Here is a demo : http://jsfiddle.net/wared/RK6X7/.

这是一个演示:http: //jsfiddle.net/wared/RK6X7/

回答by Ankit Tyagi

Call function within other function :

在其他函数中调用函数:

function abc(){    
    var a = firstFunction();    
}

function firstFunction() {
    Do something;
    return somevalue 
}

回答by nrsharma

You can do this for sure. Have a look below

你可以肯定地做到这一点。看看下面

function fnOne(){
  // do something
  return value;
}


function fnTwo(){
 var strVal= fnOne();
//use strValhere   
 alert(strVal);
}