2017-07-19 61 views
-6

我想知道如何添加/删除项目到数组,取决于它是否已经在那里。从数组中添加/删除项目 - javascript

基本上,我有一个项目列表,每个项目都有自己的ID,我想添加或删除它取决于它是否已经在篮子数组中,并指示(与CSS)是否已经在那里。

在此先感谢。

+1

到目前为止,你已经尝试过什么? –

+1

你有什么尝试?张贴一些代码。 https://stackoverflow.com/help/how-to-ask – mcgraphix

+7

这是你应该真的能够谷歌的那种。 '如何向数组添加项目','如何检查数组中是否存在元素'... –

回答

0

您可以使用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.