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

前端 未结 6 851
傲寒
傲寒 2020-12-03 02:02

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 ex

相关标签:
6条回答
  • 2020-12-03 02:19

    Call function within other function :

    function abc(){    
        var a = firstFunction();    
    }
    
    function firstFunction() {
        Do something;
        return somevalue 
    }
    
    0 讨论(0)
  • 2020-12-03 02:26

    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.

    For example:

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

    Demo

    0 讨论(0)
  • 2020-12-03 02:27

    You could call firstFunction from secondFunction :

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

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

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

    Or pass the result of firstFunction as a parameter to secondFunction :

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

    Or pass firstFunction as a parameter to secondFunction :

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

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

    0 讨论(0)
  • 2020-12-03 02:29

    To copy the return value of any javascript, we can use inbuilt copy() method.

    you can use any expression, function, etc find some examples below

    1. using expresseion

    a = 245; copy(a);

    1. using function
    a = function() {
      return "Hello world!"
    }
    copy(a());
    

    Official Doc for reference

    0 讨论(0)
  • 2020-12-03 02:32

    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);
    }
    
    0 讨论(0)
  • 2020-12-03 02:44
    var captcha = '';
    //function name one
    function one(captcha){
    var captcha = captcha;
    //call another function and pass variable data
    var captcha = firstFunction(captcha); 
    };
    // second function name
    function firstFunction(captcha){
    alert(captcha);
    }
    
    0 讨论(0)
提交回复
热议问题