write a javascript multiplication function that will return two separate results

前端 未结 4 440
长情又很酷
长情又很酷 2021-01-27 01:11

As you can see from the embed below... my script is only returning one result(500). How can I rewrite my code so that I get both results? Thank you in advance for your advice.

相关标签:
4条回答
  • 2021-01-27 01:25

    You can return a string instead of 2 separate number and then, split it into two number. Something like this:

    function multiplier(number) {
      return number * 20 + '|' + number * 1;
    }
    
    var output = multiplier(20)
    console.log(output.split('|')[0], output.split('|')[1]);

    0 讨论(0)
  • 2021-01-27 01:33

    Or alternatively....

    function multiplier() {
      return { result1: 25 * 20, result2: 25 * 1 }
    }

    0 讨论(0)
  • 2021-01-27 01:50

    A function can only return one thing. A generator function (function*) however can yield as many numbers as you want:

     function* multiplier() {
       yield 25 * 20;
       yield 25 * 1;
     }
    
     console.log(...multiplier())
    

    You could also turn the results into an array easily:

    const array = [...multiplier()];
    

    (No this is not the easiest way, but im trying to propagate some cool js :))

    0 讨论(0)
  • 2021-01-27 01:50

    You can try the following approach

    function multiplier() {
        var number = 25;
        var multiplier20 = 20;
        var res1 = 0;
        var res2 = 0;
        if (number && multiplier20); {
            res1 =  number * multiplier20;
        }
        var multiplier1 = 1;
        if (number && multiplier1); {
            res2 =  number * multiplier1;
        }
        return {res1,res2};
    }
    var ret = multiplier();
    console.log(ret);

    0 讨论(0)
提交回复
热议问题