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

array.remove(value);

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


当前回答

我喜欢这个单行道:

arr.includes(val) && arr.splice(arr.indexOf(val), 1)
  • 欧 6(无 (没有) (没有) (没有) (没有)Internet 探索器支助))
  • 在原地清除。
  • 快速: 不重复重复重复或重复 。
  • 支持删除这些值nullundefined

作为原型

// remove by value. return true if value found and removed, false otherwise
Array.prototype.remove = function(val)
{
    return this.includes(val) && !!this.splice(this.indexOf(val), 1);
}

(是的,我读了所有其他的答案 却找不到一个结合的答案)includessplice在同一行中。 )

其他回答

function array_remove(arr, index) {
    for (let i = index; i < arr.length - 1; i++) {
        arr[i] = arr[i + 1];
    }
    arr.length -= 1;
    return arr;
}
my_arr = ['A', 'B', 'C', 'D'];
console.log(array_remove(my_arr, 0));
let array = [5,5,4,4,2,3,4]    
let newArray = array.join(',').replace('5','').split(',')

如果您想要删除一个当前项目, 此示例将有效 。

我找到了这个博客文章,

9 从 JavaScript 阵列中删除元素的方法 - 附加如何安全清除 JavaScript 阵列

我更喜欢用filter():

var filtered_arr = arr.filter(function(ele){
   return ele != value;
})

从数组中删除项目的最佳方法是使用过滤法。.filter()返回没有过滤过的项目的新数组。

items = items.filter(e => e.id !== item.id);

这个.filter()将当前项目推到过滤的阵列中。更多信息过滤过滤器 在这里.

由你决定如何行动。

一种做法是使用splice从数组中删除项目的方法 :

let array = [1, 2, 3]
array.splice(1, 1);
console.log(array)

// return [1, 3]

但要确保您通过第二个参数,否则最终会删除索引后的全部数组。

第二种办法是使用filter其好处在于它是不可改变的 这意味着您的主数组不会被操纵 :

const array = [1, 2, 3];
const newArray = array.filter(item => item !== 2)
console.log(newArray)

// return [1, 3]