Making Javascript function accounts

Asked

Viewed 170 times

-2

Hello, I have to multiply using the function, are 3 calculations. When I do the following structure, only the last result appears in Return.

function multiplicar(){
  return (7*5), (7*10), (50*0.5);
}

I tried using variation and it didn’t work either

function multiplicar(numeroA,numeroB,numeroC){
  var numeroA = 7*5;
  var numeroB = 7*10;
  var numeroC = 50*0.5
  var resultado = numeroA,numeroB,numeroC;
  return resultado

You could help me by pointing out where I’m going wrong Thank you :)

  • Cannot return multiple values with comma as you are doing. Also show where you are using the supposed return of the function.

2 answers

0

Hello.

The comma operator evaluates the value of its operands (from left to right) and returns the value of the last operand.

Use + instead of the ,.

Solution:

console.log(multiplicar([7,5],[7,10],[50,0.5]));
// retorna: 130

function multiplicar(numA,numB,numC){
  var numeroA = numA[0]*numA[1];
  var numeroB = numB[0]*numB[1];
  var numeroC = numC[0]*numC[1];
  var resultado = numeroA+numeroB+numeroC;
  return resultado;
}

Case wanted to return each result:

console.log(multiplicar([7,5],[7,10],[50,0.5]));
/* retorna:
35
70
25
*/

function multiplicar(numA,numB,numC){
  var numeroA = numA[0]*numA[1];
  var numeroB = numB[0]*numB[1];
  var numeroC = numC[0]*numC[1];
  var resultado = numeroA+"\n"+numeroB+"\n"+numeroC;
  return resultado;
}

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operador_Virgula

  • i can validate these values so that each one appears on a line, break line in case?

  • Yes. Use var resultado = numeroA+"\n"+numeroB+"\n"+numeroC;

0

Voce wants to multiply the results and display in a string ? I recommend using:

const multiplicar = (n1, n2) => n1 * n2 
const resultado = multiplicar(7,5) + ', ' + multiplicar(7,10) + ', ' + multiplicar(50,0.5)
console.log(resultado)
// 30,70,25

Browser other questions tagged

You are not signed in. Login or sign up in order to post.