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

array.remove(value);

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


当前回答

我想根据ECMAScript 6. 假设你的阵列如下:

let arr = [1,2,3,4];

如果您想要删除像 2 这样的特殊索引, 请写下以下代码 :

arr.splice(2, 1); //=> arr became [1,2,4]

但如果您想要删除一个特殊项目, 如 3 和您不知道它的索引, 做如下 :

arr = arr.filter(e => e !== 3); //=> arr became [1,2,4]

提示 : 请使用箭头函数进行过滤回击, 除非您会得到空数组 。

其他回答

 const Delete = (id) => {
      console.log(id)
     var index = Array.map(function(e){
      return e.id;
     
     }).indexOf(id);
     Array.splice(index,1);
     
}

我张贴我的代码,删除一个阵列元素, 并缩短阵列长度 。

function removeElement(idx, arr) {
    // Check the index value
    if (idx < 0 || idx >= arr.length) {
        return;
    }
    // Shift the elements
    for (var i = idx; i > 0; --i) {
        arr[i] = arr[i - 1];
    }
    // Remove the first element in array
    arr.shift();
}

使用 jQuery. grep () :

var y = [1, 2, 3, 9, 4] var 删除项目 = 9; y = jQuery.grep(y, 函数(价值) {返回值 = demotephle; }; 控制台. log(y) <Src=" https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"\\/pict>

Array.prototype.removeItem = function(a) {
    for (i = 0; i < this.length; i++) {
        if (this[i] == a) {
            for (i2 = i; i2 < this.length - 1; i2++) {
                this[i2] = this[i2 + 1];
            }
            this.length = this.length - 1
            return;
        }
    }
}

var recentMovies = ['Iron Man', 'Batman', 'Superman', 'Spiderman'];
recentMovies.removeItem('Superman');

根据索引删除

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

/**
* 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]