简体   繁体   中英

Remove Item from array using Javascript

I have one javascript array i will store this array in local Storage

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

Above is the array result and i will set the array values to local Storage

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
}

function call

var id = 1;
removeItem(id);

The first positioned array value is not removing from Array items. All other values will perfectly remove using this function But the first value in array not removing from array. Can anyone please suggest the better option?

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

Try to used this function.

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

For example :

removeItem(result,1);

A simple way to remove items from an array is the following :

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

use like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM