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

array.remove(value);

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


当前回答

此函数从特定位置的数组中删除元素。

array.remove(position);

Array.prototype.remove = function (pos) {
    this.splice(pos, 1);
}

var arr = ["a", "b", "c", "d", "e"];
arr.remove(2); // remove "c"
console.log(arr);

如果您不知道要删除的项目的位置, 请使用这个 :

array.erase(element);

Array.prototype.erase = function(el) {
    let p = this.indexOf(el); // indexOf use strict equality (===)
    if(p != -1) {
        this.splice(p, 1);
    }
}

var arr = ["a", "b", "c", "d", "e"];
arr.erase("c");
console.log(arr);

其他回答

更现代一点ECMAScript 2015(原称和谐或ES6)方法。

const items = [1, 2, 3, 4];
const index = 2;

然后:

items.filter((x, i) => i !== index);

弹出 :

[1, 2, 4]

您可以使用贝贝以及 a 和 a多元填充服务以确保在浏览器之间得到很好的支持。

只删除第一个34年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄、年龄34:

ages.splice(ages.indexOf(34), 1);

或者您可以在全球定义一种方法 :

function remove(array, item){
    let ind = array.indexOf(item);
    if(ind !== -1)
        array.splice(ind, 1);
}

将所有年龄都除去34:

ages = ages.filter(a => a !== 34);

除了所有这些解决方案之外, 它也可以用阵列来完成. 减量...

const removeItem = 
    idx => 
    arr => 
    arr.reduce((acc, a, i) =>  idx === i ? acc : acc.concat(a), [])

const array = [1, 2, 3]
const index = 1

const newArray = removeItem(index)(array) 

console.log(newArray) // logs the following array to the console : [1, 3]

...或者一个循环函数(诚实地说不是那么优雅...也许有人有更好的循环解决方案? ? )...

const removeItemPrep = 
    acc => 
    i => 
    idx => 
    arr => 

    // If the index equals i, just feed in the unchanged accumulator(acc) else...
    i === idx ? removeItemPrep(acc)(i + 1)(idx)(arr) :

    // If the array length + 1 of the accumulator is smaller than the array length of the original array concatenate the array element at index i else... 
    acc.length + 1 < arr.length ? removeItemPrep(acc.concat(arr[i]))(i + 1)(idx)(arr) : 

    // return the accumulator
    acc 

const removeItem = removeItemPrep([])(0)

const array = [1, 2, 3]
const index = 1

const newArray = removeItem(index)(array) 

console.log(newArray) // logs the following array to the console : [1, 3]

spolice () 函数能够将数组中的项目还给您, 从特定的索引中删除项目 / 项 :

function removeArrayItem(index, array) {
    array.splice(index, 1);
    return array;
}

let array = [1,2,3,4];
let index = 2;
array = removeArrayItem(index, array);
console.log(array);

检查一下这个代码 每个代码都有效主浏览器.

remove_item = function(arr, value) {
 var b = '';
 for (b in arr) {
  if (arr[b] === value) {
   arr.splice(b, 1);
   break;
  }
 }
 return arr;
};

var array = [1,3,5,6,5,9,5,3,55]
var res = remove_item(array,5);
console.log(res)