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

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

本文关键字:javascript 元素 条件 包含 数组 何检查 检查      更新时间:2023-09-26

代码:

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;
        }
    }
}

contains替换为indexOf

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

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