使用 Javascript 从数组中删除 Item

Remove Item from array using Javascript

本文关键字:删除 Item 数组 Javascript 使用      更新时间:2023-09-26

我有一个javascript数组,我将把这个数组存储在本地存储中

 var result;     
 result = [1,2,3,4,5];
 localStorage.setItem('result', JSON.stringify(result));

以上是数组结果,我将数组值设置为本地存储

function removeItem(Id){
    result= JSON.parse(localStorage.getItem('result'));// get array values from local Strorage
    var index = result.indexOf(Id);// find index position
    result.splice(index , 1); //and removing the Id from array
    localStorage.setItem('result', JSON.stringify(result));// result set to local storage
}

函数调用

var id = 1;
removeItem(id);

第一个定位的数组值不会从数组项中删除。所有其他值将使用此函数完美删除,但数组中的第一个值不会从数组中删除。任何人都可以建议更好的选择吗?

要删除第一个元素,您必须使用索引值 = 0 而不是 1

尝试使用此函数。

function removeItem(arr) {
    var what, a = arguments, len = a.length, ax;
    while (len  > 1 && arr.length) {
        what = a[--len ];
        while ((ax= arr.indexOf(what)) !== -1) {
            arr.splice(ax, 1);
        }
    }
    return arr;
}

例如:

removeItem(result,1);

从数组中删除项目的一种简单方法如下:

// as a function
function removeitem(item, arr){
    var i; while( ( i = arr.indexOf(item)) != -1)arr.splice(i, 1);
}

像这样使用

var result;     
result = [1,2,3,4,5];
removeitem(1, result);