在数组中添加或删除元素

时间:2016-09-05 17:56:57

标签: javascript arrays

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

这是我的代码:

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");
    }
}

7 个答案:

答案 0 :(得分:1)

内置popshift方法从两端删除。

如果要删除数组中间的元素,可以使用repository pattern

function removeElementAtIndex(arr, i) {
  Array.prototype.splice.call(arr, i, 1);
}

如何确定某个元素>数组中的取决于您在&#34;中的含义&gt;。&#34;。

indexOf非常好,但有一个极端情况:[NaN].indexOf(NaN)-1因为NaN !== NaN

假设您不担心NaN,您可以

function togglePresent(arr, el) {
  var idx = arr.indexOf(el);
  if (idx >= 0) {
    arr.splice(idx, 1);
  } else {
    arr.push(el);
  }
}

如果你关心,你可以尝试不同的策略,在idx时重新计算isNaN(el)

注意:这只会删除elarr的一个实例。

答案 1 :(得分:1)

您的逻辑似乎不正确 - 假设您在amiNotifies中有2个项目并且您想要添加第三个新值 - 第一次for循环运行(i = 0),它将添加项目(伪) ,第二次(i = 1)它将删除添加的项目(伪),最终不会添加新项目,你应该根据amiNotifies中存在的添加和删除逻辑进行修改。

你应该使用 splice 操作从amiNotifies中删除值。

答案 2 :(得分:1)

您错误地检查了重复项,只需将每个项目与进行比较。你需要循环遍历所有项目以查看它是否匹配任何项目,然后根据匹配执行添加/删除。以下代码适合您。

function checkAmi(pseudo, id) {
    var info = ({
        pseudo: pseudo,
        id: id
    });
    var getIndexOf = function (psdu) {
        for (var i = 0; i < amisNotifies.length; i++) {
            if (amisNotifies[i].pseudo === psdu) {
                return i;
            }
        }

        return -1;
    };

    if (amisNotifies.length > 0) {
        var index = getIndexOf(pseudo);
        if (index > -1) {
            //so already exists. now remove it.
            Array.prototype.splice.call(amisNotifies, index, 1);
            $("#checkAmi" + id).addClass("fa-circle-o");
            $("#checkAmi" + id).removeClass("fa-check-circle-o");
        }
        else {
            //does not exist, now add it
            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");
    }
}

答案 3 :(得分:1)

已测试

这是另一个简单的解决方案:

var newItem = "NEW_ITEM_TO_ARRAY";
var array = ["OLD_ITEM_1", "OLD_ITEM_2"];
array.indexOf(newItem) === -1 ? array.push(newItem) : array.splice(array.indexOf(newItem), 1);

console.log(array)
如果找不到

indexOf,它将返回-1,这意味着如果不存在,则将添加..以获取更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

否则,如果找到它,则意味着它存在,您将使用拼接将其删除,第一个参数是索引,第二个参数是您将删除多少个元素:有关更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

答案 4 :(得分:0)

您可以做到

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
  }
}

答案 5 :(得分:0)

这就是我用的。 Typescript,但是提示类型提示要在JS中使用。

export function addOrRemove<T>(source: T[], candidate: T, comparator?: (a: T, b: T) => boolean): T[] {
  const c = comparator || ((a, b) => a == b)
  const e = source.find(i => c(i, candidate))
  return e ? source.filter(i => !c(i, candidate)) : [...source, candidate]
}

它将不变地切换数组元素(如果存在则删除,如果不存在则添加)。作为最后一个参数的可选比较器函数可用于比较非标量值,例如对象。

答案 6 :(得分:0)

在其中一个 vue-3 项目中,我是这样做的:

<script>
import { defineComponent, ref } from 'vue';

export default defineComponent({
  setup() {
    const itemsSelected = ref([]);

    const addOrRemoveItem = (itemId) => {
      const exists = itemsSelected.value.includes(itemId);

      if (exists) {
        itemsSelected.value = itemsSelected.value.filter((id) => id !== itemId);
      } else {
        itemsSelected.value.push(itemId);
      }
    };

    return { addOrRemoveItem };
  },
});
</script>