简体   繁体   中英

How can I make this function work?

I have two arrays set up that I wish to multiply each value within each together. Then I want to get the total value in the form of a variable. I will post what I have below. I think my problem may be that I am not sure how to get each run of the code to add together?

var flatQty=[];
flatQty[0]= document.getElementById("flats1").value;
flatQty[1]= document.getElementById("flats2").value;
flatQty[2]= document.getElementById("flats3").value;
flatQty[3]= document.getElementById("flats4").value;
flatQty[4]= document.getElementById("flats5").value;

var flatWidth=[];
flatWidth[0]=document.getElementById("flatwidth1").value;
flatWidth[1]=document.getElementById("flatwidth2").value;
flatWidth[2]=document.getElementById("flatwidth3").value;
flatWidth[3]=document.getElementById("flatwidth4").value;
flatWidth[4]=document.getElementById("flatwidth5").value;

for (var i=0;i<5;i++)
{
var flatCharge=flatWidth[i]*2*flatQty[i];
}

document.getElementById("flatTest").innerHTML=flatCharge; 

When I run the code nothing is printed into the id="flatTest".

Your problems is that you are redefining your flatCharge inside the loop, therefore it's not correct outside the loop. In addition, you are not adding the values, but replacing them on every iteration of the loop. Change the loop to this:

var flatCharge = 0;
for (var i = 0; i < 5; i++) {
    flatCharge += flatWidth[i] * 2 * flatQty[i];
};

document.getElementById("flatTest").innerHTML = "" + flatCharge; 

and it should work.

.value properties are strings , not numbers . so you should be careful how you handle them. Multiplication actually works for strings, but not for addition where the + operator performs concatenation instead.

There are numerous methods of converting from string to number:

  • +s - will convert the expression s into a number
  • parseFloat(s)
  • parseInt(s, 10) for whole numbers

The actual problem in your code is that you're overwriting the calculated value in each pass using the = operator instead of += .

I suggest refactoring your entire code thus to avoid all of the repetition:

var flatCharge = 0;
for (var i = 1; i <= 5; ++i) {
    var qty = +document.getElementById('flats' + i).value;
    var width = +document.getElementById('flatwidth' + i).value;

    if (!isNaN(qty) && !isNaN(width)) {
        flatCharge += 2 * qty * width;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM