write a javascript multiplication function that wi

2019-03-02 07:30发布

问题:

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.

function multiplier() {
    var number = 25;
    var multiplier20 = 20;
    if (number && multiplier20); {
        return number * multiplier20;
    }
    var multiplier1 = 1;
    if (number && multiplier1); {
        return number * multiplier1;
    }
}
multiplier();

EDIT: hey guys thanks for the help. but I figured out what the problem was... I am not supposed to be returning an object only an number. So how do I edit this code to make it return only two numbers???

回答1:

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 :))



回答2:

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);



回答3:

Or alternatively....

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



回答4:

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]);