javascript 未插入数组

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

最佳答案

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/

相关文章:

javascript - 无法在 jQuery 中捕获 Ctrl+Alt+箭头键事件

javascript - 如何为google表单预填链接生成二维码

javascript - 如何访问 Dynatable AJAX 调用请求的 JSON 中的附加数据

javascript - 在两个函数中两次使用 console.log 时只打印一个 undefined

javascript - Facebook 如何检测到您不在?

javascript - 获取 jQuery UI 主题列表 - 来自 URL(同源策略)

javascript - 使用 Jquery 将类添加到 TextBox 时出现问题

javascript - 如何解决错误 "ERR! code ELIFECYCLE"?

javascript - 如何找出数组中相似的对象 - React JS

javascript - 如何配置 emacs 以编辑包含 Javascript 的 HTML 文件?