0

配列の内容を変数に入れて、ifステートメントで使用しようとしています。私の目標は、配列の最大数を見つけて、対応する「月」とともに表示することです。最大数を達成することができましたが、ifステートメントが正しく機能するようにi = maxMonthIndexを使用する必要がありますか?

function displayHighestSalary() {

    console.log("Inside displayArrayContents function");

    var maxFinal;
    var max = monthlySales[0];
    var maxMonth;
    var maxMonthIndex;

    console.log("monthlySales.length = " + monthlySales.length);


    //Loop through array and build display string
    for (var i = 0; i < monthlySales.length; i++)  
    {
        if (monthlySales[i] > max) {
            max = monthlySales[i];
            maxMonthIndex = **??????**;
        }
    }


    console.log("max = " + max)

    if (maxMonthIndex = monthlySales[0]) {
        maxMonth = "january";
    }
    else if (maxMonthIndex = monthlySales[1]) {
        maxMonth = "February";
    }
    else if (maxMonthIndex = monthlySales[2]) {
        maxMonth = "March";
    }
    else if (maxMonthIndex = monthlySales[3]) {
        maxMonth = "April";
    }
    else if (maxMonthIndex = monthlySales[4]) {
        maxMonth = "May";
    }
    else if (maxMonthIndex = monthlySales[5]) {
        maxMonth = "June";
    }
    else if (maxMonthIndex = monthlySales[6]) {
        maxMonth = "July";
    }
    else if (maxMonthIndex = monthlySales[7]) {
        maxMonth = "August";
    }
    else if (maxMonthIndex = monthlySales[8]) {
        maxMonth = "September";
    }
    else if (maxMonthIndex = monthlySales[9]) {
        maxMonth = "October";
    }
    else if (maxMonthIndex = monthlySales[10]) {
        maxMonth = "November";
    }
    else if (maxMonthIndex = monthlySales[11]) {
        maxMonth = "December";
    }

    maxFinal = addCommas(max);

    //Display results
    document.getElementById('divDisplayHighest').innerHTML = "$" + maxFinal + " " +     maxMonth;
}
4

1 に答える 1

2

maxMonthIndexに設定i

//Loop through array and build display string
for (var i = 0; i < monthlySales.length; i++)  
{
    if (monthlySales[i] > max) {
        max = monthlySales[i];
        maxMonthIndex = i;
    }
}

割り当てステートメントをに変更===し、最大値ではなくインデックス(数値)と比較します。

if (maxMonthIndex === 0) {
    maxMonth = "january";
}
// and so on

さらに良い:

// add this up top with all of your other variable declarations
var monthLabels = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

//then...
//Loop through array and build display string
for (var i = 0; i < monthlySales.length; i++)  
{
    if (monthlySales[i] > max) {
        max = monthlySales[i];
        maxMonthIndex = i;
    }
}
// now that you know the maxMonthIndex, get the label
maxMonth = monthLabels[maxMonthIndex]; 
于 2012-07-18T23:11:14.057 に答える