如何在javascript中检查数组包含元素的条件?

时间:2016-01-17 14:28:34

标签: javascript arrays json if-statement

代码:

monthArray = ["jan 2009", ..., "dec 2009"];

jsonFile包含:

[
    {
        "month": "Aug 2012",
        "no_Of_Commits": 1
    },
    {
        "month": "Jun 2012",
        "no_Of_Commits": 1
    },
    {
        "month": "Apr 2012",
        "no_Of_Commits": 6
    }
]
function populate(jsonFile) {
    tempJson = jsonFile;

    for (var i = 0; i < monthArray.length; i++)
    {       
        if (monthArray.contains(tempJson[i]["month"]))       // condition Not working suggest anything else
        {
            console.log("yes");
            tempJson[i]["no_Of_Commits"] = tempJson[i]["no_Of_Commits"];
        }
        else
        {
            console.log("NO"); 
            jsonFile[i]["no_Of_Commits"] = 0;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

contains替换为indexOf

if ( monthArray.indexOf( tempJson[i]["month"] ) !== -1 ) {...

当你在一个数组上进行迭代,并从另一个数组中获取值时,最好确保两个数组具有相同数量的索引等。