如何从数组中删除一个特定值? 类似 :

array.remove(value);

制约:我必须使用核心 JavaScript 。 框架不允许 。


当前回答

您只需要按元素或索引过滤 :

var num = [5, 6, 5, 4, 5, 1, 5]; var result1 = num.filter((el, index) => el != 5) // for remove all 5 var result2 = num.filter((el, index) => index != 5) // for remove item with index == 5 console.log(result1); console.log(result2);

其他回答

不可改变和一班制方式:

const newArr = targetArr.filter(e => e !== elementToDelete);

根据索引删除

函数返回在索引中没有元素的数组副本 :

/**
* removeByIndex
* @param {Array} array
* @param {Number} index
*/
function removeByIndex(array, index){
      return array.filter(function(elem, _index){
          return index != _index;
    });
}
l = [1,3,4,5,6,7];
console.log(removeByIndex(l, 1));

$> [ 1, 4, 5, 6, 7 ]

以值删除

函数返回没有值的数组副本。

/**
* removeByValue
* @param {Array} array
* @param {Number} value
*/
function removeByValue(array, value){
      return array.filter(function(elem, _index){
          return value != elem;
    });
}
l = [1,3,4,5,6,7];
console.log(removeByValue(l, 5));

$> [ 1, 3, 4, 6, 7]

正在删除带有索引和相交点的值 !

function removeArrValue(arr,value) {
    var index = arr.indexOf(value);
    if (index > -1) {
        arr.splice(index, 1);
    }
    return arr;
}

如果您想要删除删除位置的新数组, 您总是可以删除特定元素并过滤数组。 它可能需要为不执行过滤方法的浏览器扩展数组对象, 但从长远来看, 它比较容易, 因为您所做的只是:

var my_array = [1, 2, 3, 4, 5, 6];
delete my_array[4];
console.log(my_array.filter(function(a){return typeof a !== 'undefined';}));

它应显示[1、2、3、4、6]。

您可以对每个数组项进行循环, 如果在您的数组中存在的话, 可以复制并连接它 。

function destroy(arr, val) {
    for (var i = 0; i < arr.length; i++) if (arr[i] === val) arr.splice(i, 1);
    return arr;
}