简体   繁体   中英

How to check the condition the array contains the element in javascript?

Code:

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

The jsonFile contains:

[
    {
        "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;
        }
    }
}

Replace contains with indexOf

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

and as you're iterating over one array, and getting values from another array, you better make sure both arrays have the same number of indices etc.

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