我正在循环一个 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;
}
最佳答案
and if not it should push it into the array
您错过了不是。仅当它已经在数组中时,才将其插入数组中。添加logical not operator ( ! ) :
if ( ! isInArray(treeSplit[childCount], aliasGroup) ) {
aliasGroup.push(treeSplit[childCount]);
}
关于javascript 未插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34724506/