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

array.remove(value);

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


当前回答

只将前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);

其他回答

从数组中删除一个特定元素, 可以在过滤器选项的一行内完成, 它得到所有浏览器的支持 : https:// caniuse. com/ #search=filter% 20arary

function removeValueFromArray(array, value) {
    return array.filter(e => e != value)
}

我在这里测试了此函数 : https://bit.dev/joshk/jotils/remove-value- from-array/~code#test.ts

您可以从数组中添加一个原型函数来“ 移除” 元素 。

以下示例显示当我们知道一个元素的索引时, 如何简单地从数组中删除一个元素。 我们用它来使用 Array. filter 方法 。

Array. prototype. removeByIndex = 函数 (i) {如果 (! Number. is Integer(i) {i < 0) {/ i 必须是一个整数返回它;} 返回此. filter( f, indx) { indx! = i)} var a = [5, - 89, 2 * 2, " some string", null, froid, 未定义, 20, null, 5]; var b = a. remove ByIndex(2); control.log(a); control.log(b);

有时候我们不知道元素的索引

Array. prototype. remove = 函数 (i) { 返回此. filter (f \ \ f \ f y = i) {var a = [5, - 89, 2 ( 2 * 2), “ 一些字符串 ” 无效, 错误, 未定义, 20, 无效, 5] ; var b = a. remove(5). remove (null); 控制台. log (a); 控制台. log (b) / 它消除了所有搜索值的发生次数 。

但是,当我们只想要删除搜索值的首次出现时, 我们可以在函数中使用 Array. indexof 方法 。

Array. prototype. removeFirst = 函数 (i) {i = this.indexof (i); if (! Number. is Integer (i) {i < 0) {返回此 ;} 返回此. filter (f, indx) { indx = indx ! = i)} var a = [5, - 89, 2 * 2, " some string", null, fraud, 未定义, 20, null, 5]; var b = a.remove First(5).remove First(nell); translavor.log(a) ; controad.log(b);

您可以使用 lodash _. pull( 调和数组)、 _. pullAt( 调和数组) 或 _. 。 (不变换数组)

var array1 = ['a', 'b', 'c', 'd']
_.pull(array1, 'c')
console.log(array1) // ['a', 'b', 'd']

var array2 = ['e', 'f', 'g', 'h']
_.pullAt(array2, 0)
console.log(array2) // ['f', 'g', 'h']

var array3 = ['i', 'j', 'k', 'l']
var newArray = _.without(array3, 'i') // ['j', 'k', 'l']
console.log(array3) // ['i', 'j', 'k', 'l']

非就地解决办法

arr.slice(0,i).concat(arr.slice(i+1));

arr = [10, 20, 30, 40, 50] (i) = 2;// 位置删除(从0开始) ; r = ar. selice (0, i). concat (arr. slice (i+1)); 控制台.log(r);

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');