dm8021122
dm8021122

Reputation: 47

for loop pushing to many values into an array

Note: Jquery or JS resolutions. I have an array called "Decimal" That receives 11 decimal values with the whole number removed (Ex: 0.25)

If I run these 7 if statements against a single value in my Decimal array like below, I get 1 value in the "Fraction" array, which is what I wanted to happen to confirm that the logic in the if() statements is correct.

        if (Decimal[1] <= 0.125) {Fraction.push('1/8');}
        if (Decimal[1] <= 0.25) {Fraction.push('1/4');}
        if (Decimal[1] <= 0.375) {Fraction.push('3/8');}
        if (Decimal[1] <= 0.50) {Fraction.push('1/2');}
        if (Decimal[1] <= 0.625) {Fraction.push('5/8');}
        if (Decimal[1] <= 0.75) {Fraction.push('3/4');}
        if (Decimal[1] <= 1) {Fraction.push('7/8');}

As soon as I put those 7 if statements into a for loop I get 44 values in the Fraction Array ( I was expecting 11). See Code Below:

for (var t = 0; t < Decimal.length; t++) {
        if (Decimal[t] <= 0.125) {Fraction.push('1/8');}
        if (Decimal[t] <= 0.25) {Fraction.push('1/4');}
        if (Decimal[t] <= 0.375) {Fraction.push('3/8');}
        if (Decimal[t] <= 0.50) {Fraction.push('1/2');}
        if (Decimal[t] <= 0.625) {Fraction.push('5/8');}
        if (Decimal[t] <= 0.75) {Fraction.push('3/4');}
        if (Decimal[t] <= 1) {Fraction.push('7/8');}
    }

Upvotes: 0

Views: 145

Answers (2)

dinkydani
dinkydani

Reputation: 151

You need else if statements for all but the first condition otherwise one value could match more than one statement:

for (var t = 0; t < Decimal.length; t++) {
  if (Decimal[t] <= 0.125) {Fraction.push('1/8');}
  else if (Decimal[t] <= 0.25) {Fraction.push('1/4');}
  else if (Decimal[t] <= 0.375) {Fraction.push('3/8');}
  else if (Decimal[t] <= 0.50) {Fraction.push('1/2');}
  else if (Decimal[t] <= 0.625) {Fraction.push('5/8');
  else if (Decimal[t] <= 0.75) {Fraction.push('3/4');}
  else if (Decimal[t] <= 1) {Fraction.push('7/8');}
}

Upvotes: 1

Hogan
Hogan

Reputation: 70528

not sure what test you did but this is the logic you need:

for (var t = 0; t < Decimal.length; t++) {
    if (Decimal[t] <= 0.125) {Fraction.push('1/8');}
    else
    if (Decimal[t] <= 0.25) {Fraction.push('1/4');}
    else
    if (Decimal[t] <= 0.375) {Fraction.push('3/8');}
    else
    if (Decimal[t] <= 0.50) {Fraction.push('1/2');}
    else
    if (Decimal[t] <= 0.625) {Fraction.push('5/8');}
    else
    if (Decimal[t] <= 0.75) {Fraction.push('3/4');}
    else
    if (Decimal[t] <= 1) {Fraction.push('7/8');}
}

note: it is better to use {} in the else area but I was to lazy to type all those.

Upvotes: 0

Related Questions