How to multiply arrays?

0

I made a simple code that adds the arrays, but how do I multiply them?

         

<h1>The % Operator</h1>

<p id="demo"></p>
<input type="submit" value="Multiplicacion DE VALORES MEDIANTE CICLOS, ARRAYS Y ACUMULADOR"onClick="ciclos();"/>

<script>

function ciclos() {

  var arrayU = new Array(3);
  var f;
  for (f=0;f<arrayU.length;f++) { // ARRAY LENGTH = 3 = FOR = 0, 1 , 3
    var v = prompt('Ingresa los 3 valores a multiplicar:','');
    arrayU[f] = parseInt(v);
  }
  var total = 0;
  //var multiplicacion;
  //var number;
  for (f=0;f<arrayU.length;f++) {
  total = arrayU[f] + total;
  }
    document.write(total);    
}



</script>

</body>
</html>

I know it can be done like that, but it's very manual:

function arrayManual() {
var arrayU = new Array(3);

arrayU[0] = prompt('Ingresa el 1er numero:','');
  arrayU[1] = prompt('Ingresa el 2do numero:','');
  arrayU[2] = prompt('Ingresa el 3er numero:','');


document.write(arrayU[0] * arrayU[1] * arrayU[2]);

}
    
asked by Eduardo Sebastian 24.04.2017 в 18:59
source

2 answers

2

You can do it in the same way as the sum, you just have to change a couple of things; I present 2 ways to do it.

the part of receiving the numbers is exactly the same.

var arrayU = new Array(3);
var f;
for (f=0;f<arrayU.length;f++) { // ARRAY LENGTH = 3 = FOR = 0, 1 , 3
  var v = prompt('Ingresa los 3 valores a multiplicar:','');
  arrayU[f] = parseInt(v);
}

form 1: equal the total to 1 and use the same cycle that adds the array

var total = 1;
for (f=0;f<arrayU.length;f++) {
  total = arrayU[f] * total;
}
document.write(total);

form 2: the first time you enter the cycle, assign the value to total

var total = 0;
for (f=0;f<arrayU.length;f++) {
  if(f === 0){
    total = arrayU[f];
  } else {
    total = arrayU[f] * total;  
  }
}
document.write(total);
    
answered by 24.04.2017 / 19:23
source
0

Instead of asking for each number, ask that the numbers be entered once, for example, separated by commas. Then divide the input by using split and finally use reduce to multiply the numbers:

const numbers = prompt('Ingresa los números separados por comas').split(',');
const result = numbers.reduce((acc, n) => n * acc);
console.info(result);
    
answered by 24.04.2017 в 19:44