Cattle customer network front-end programming: delete a specific array element

For me this white front-end, the beginning only know that an idea to solve this problem:

//第一种方法
        function remove(arr, item) {
            var arr1=new Array();
            for(var i = 0;i < arr.length;i++){
                if(arr[i]!=item){
                    arr1.push(arr[i]);
                }
            }
            return arr1;
        }

Later, others do see a bit and found that there are other ways, by the way learn about:

// The second method: using splice and slice
         // splice method changes the original array, you need the original array to a new array of transfer 
        function remove1 (arr, Item) {
             // use the original data array slice method of assigning all to arr1 array 
            var arr1 = arr.slice ( 0 );
             // splice (X, Y): X deleted starting from the element of Y element 
            for ( var I = 0 ; I <arr1.length; I ++ ) {
                 IF ( of arr1 [I] === Item) { 
                    arr1.splice (I, . 1 ); 
                    I - ; 
                } 
            } 
            return of arr1; 
        }
// third method: using arr.filter (function) Method ----> only return arr array consistent with the data value function
         // filter array method does not change the original 
        function remove2 (arr, Item) {
             // A method of using the first filter 
            return arr.filter (function (Element) {
                 return Element =! Item; 
            }) 
            // use the second method filter 
            function A (Element) {
                 return Element =! Item; 
            } 
            return arr.filter ( A); 
        }

All three methods tested

Guess you like

Origin www.cnblogs.com/purple-windbells/p/11244193.html