我绕着一个json对象循环,并在对象中获取一个包含逗号分隔字符串的项目,然后拆分该字符串并检查其是否在数组中,如果不是,则应将其推入数组。问题是,它永远不会推入阵列

for (var item = 0; item < rules.length; item++) {
    //we now need to split the item by its delimiter which is a comma ','
    var treeSplit = rules[item].tree.split(',');

    if (treeSplit.length - 1 != childCount) {
        if (isInArray(treeSplit[childCount], aliasGroup)) {
            aliasGroup.push(treeSplit[childCount]);
        }
    } else {
        //do something
    }


这是我的isInArray函数,它需要一个值和数组

function isInArray(value, array) {
    return array.indexOf(value) > -1;
}

最佳答案

如果没有,则应将其推入数组


你错过了没有。仅当阵列中已有阵列时,才将其推入阵列。添加logical not operator ( ! )

if ( ! isInArray(treeSplit[childCount], aliasGroup) ) {
    aliasGroup.push(treeSplit[childCount]);
}

10-06 01:33