javascript - 在数组中添加或删除元素

标签 javascript arrays

如果对象不存在,我想将它添加到数组中,如果它已经存在于数组中,我想将其删除。
我成功添加了第一项,但如果我在数组中添加其他对象,它就不起作用。我可以删除第一项。有个bug,不知道为什么。

这是我的代码:

function checkAmi(pseudo, id) {
    var info = ({
        pseudo: pseudo,
        id: id
    });
    if (amisNotifies.length > 0) {
        // iterate over each element in the array
        for (var i = 0; i < amisNotifies.length; i++) {
            console.log(angular.toJson(amisNotifies[i].pseudo));
            // look for the entry with a matching `code` value
            if (amisNotifies[i].pseudo === pseudo) {
                amisNotifies.removeValue('pseudo', pseudo);
                $("#checkAmi" + id).addClass("fa-circle-o");
                $("#checkAmi" + id).removeClass("fa-check-circle-o");
            } else {
                amisNotifies.push(info);
                $("#checkAmi" + id).removeClass("fa-circle-o");
                $("#checkAmi" + id).addClass("fa-check-circle-o");
            }
        }
    } else {
        amisNotifies.push(info);
        $("#checkAmi" + id).removeClass("fa-circle-o");
        $("#checkAmi" + id).addClass("fa-check-circle-o");
    }
}

最佳答案

你可以这样做

const addOrRemove = (array, item) => {
  const exists = array.includes(item)

  if (exists) {
    return array.filter((c) => { return c !== item })
  } else {
    const result = array
    result.push(item)
    return result
  }
}

关于javascript - 在数组中添加或删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39335607/

相关文章:

javascript - d3 svg 中的选择

javascript - 在 NodeJS 中解析 JSON 对象数组

javascript - 如何比较 JavaScript 中的数组?

javascript - 使用 React-Router 在路由之间传递 props

javascript - 使用 document.querySelector ('.' ).style。改变一个 div 的 *两个* CSS 属性

javascript - Highcharts:多系列柱形图中的位置散点图

python - ArrayField 中的 Django JSONField

arrays - 在 Julia 的单个数据框中保存不同长度的数组

javascript - 动态结果数组需要使用 Angular JS 与具有不同布局的表绑定(bind)

c++ - Arduino 传递多维数组