javascript没有推入数组

时间:2016-01-11 14:58:03

标签: javascript

我循环一个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;
}

1 个答案:

答案 0 :(得分:5)

  

如果 ,它应该将其推入数组

您错过了 。只有当它已经在数组中时,才将它推入数组。添加logical not operator ( ! )

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