How to multiply all values ​​in javascript

I have a form with several text fields, and the number of text fields varies depending on the values ​​that I retrieve from the database. What I'm trying to do is multiply all the values ​​of the text field values, so first I put them in an array and multiply them and send the response to the text field. But I can not find the right answer.

For example, when I have 3 text fields and I enter 1 in each text field, I should get 1x1x1 = 1, but I get the answer as 3. When I enter 2 in each text field, I should get 2x2x2 = 8, but the answer 12.

My code is as follows:

Javascript Code:

function sumfrm(form){ var totalOdds = 0; var odds = document.getElementsByTagName('input'); var n; var i; // for (i = 0; i < odds.length; ++i) { n = parseFloat(odds.item(i).value, 10); if (!isNaN(n)) { totalOdds += n*n; } } 
+4
source share
6 answers
 var totalOdds = 1; //initialize like this totalOdds = totalOdds * n // do this in your for loop 

gotta do the trick

What do you currently have for 1x1x1.

totalOdds at the beginning 0

After totalOdds += 1 * 1

equals 1

Again after the second time totalOdds += 1 * 1

equals 2

and after the third time 3

+2
source
 for (i = 0; i < odds.length; ++i) { n = parseFloat(odds.item(i).value, 10); if (!isNaN(n)) { totalOdds *= n; } } 
+1
source
 function sumfrm(form){ var totalOdds = 1; // changed var odds = document.getElementsByTagName('input'); var n; var i; // for (i = 0; i < odds.length; ++i) { n = parseFloat(odds.item(i).value, 10); if (!isNaN(n)) { totalOdds *= n; // changed } } 

Two lines changed. Now it should work correctly, brother :)

+1
source

First of all, I suggest you clear the code a bit:

  • remove the unused form argument from your function.

  • Reduce the number of local variables in your function body.

     function multiply() { var inputs = document.getElementsByTagName('input'); var result = parseFloat(inputs.item(0).value, 10) || 0; (result == 0) && return 0; for (var i = 1; i < inputs.length; ++i) { n = parseFloat(inputs.item(i).value, 10); (isNaN(n) || n == 0) ? return 0 : result *= n; } return result; } 
0
source

You take the sum of the squared numbers. Instead, do the following:

 function sumfrm(form){ var totalOdds = 1; var odds = form.getElementsByTagName('input'); var n, i; for(i = 0; i < odds.length; i++) { n = parseFloat(odds[i].value); if(!isNaN(n)) { totalOdds *= n ; } } } 
0
source

in order to do array multiplication, it would be better to use the default function in the java script “reduce”, u can push all the values ​​into the array and then do the multiplication Please try the code below. (this is ES6)

 let sum = [1, 1, 1].reduce( (prev, curr) => prev * curr ); 
0
source

Source: https://habr.com/ru/post/1382001/


All Articles