The best way to remove array element by value

后端 未结 10 1278
北荒
北荒 2020-12-25 10:18

I have an array like this

arr = [\"orange\",\"red\",\"black\",\"white\"]

I want to augment the array object defining a deleteElem()<

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-25 10:29

    Or simply check all items, create a new array with non equal and return it.

    var arr = ['orange', 'red', 'black', 'white'];
    
    console.info('before: ' + JSON.stringify(arr));
    
    var deleteElem = function ( val ) {
        var new_arr = [];
        for ( var i = 0; i < this.length; i++ ) {
            if ( this[i] !== val ) {
                new_arr.push(this[i]);
            }
        }
        return new_arr;
    };
    
    arr = deleteElem('red');
    
    console.info('after: ' + JSON.stringify(arr));
    

    http://jsfiddle.net/jthavn3m/

提交回复
热议问题