【问题标题】:Add/Remove item from array - javascript [duplicate]从数组中添加/删除项目 - javascript [重复]
【发布时间】:2017-07-19 13:11:21
【问题描述】:

我想知道如何根据它是否已经在数组中添加/删除项目。

基本上,我有一个项目列表,每个项目都有自己的 ID,我想根据它是否已经在篮子数组中添加或删除它,并指示(使用 css)它是否已经在其中。

提前致谢。

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 你试过什么?发布一些代码。 stackoverflow.com/help/how-to-ask
  • 这是您真正应该能够通过 Google 搜索到的那种东西。 '如何向数组中添加项'、'如何检查数组中是否存在元素'...

标签: javascript jquery arrays


【解决方案1】:

你可以使用jQuery内置函数$.inArray

cart = ["value1","value2","value3","value4"];  // Cart Items
var new-item = "value2";
var index = $.inArray(new-item, cart);

if(index == -1){
    // Item doesn't exist. Add this item to the cart
    cart.push(new-item);
}else{
    //Item already exists.
    //Delete that item.
    unset($array[index]);
}

console.log(cart); //Display the cart items.

【讨论】:

    猜你喜欢
    • 2021-10-03
    • 2013-08-03
    • 2015-08-19
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 2011-12-02
    • 2023-02-21
    相关资源
    最近更新 更多