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

array.remove(value);

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


当前回答

2021年更新

您的问题是如何从数组中删除一个特定项目。 您在具体项目中指的是一个数字, 例如 。 从数组中删除数字 5 。 据我了解, 您正在寻找类似 :

// PSEUDOCODE, SCROLL FOR COPY-PASTE CODE
[1,2,3,4,5,6,8,5].remove(5) // result: [1,2,3,4,6,8]

至于2021年,实现该目标的最佳途径是使用数组过滤功能:

const input = [1,2,3,4,5,6,8,5];
const removeNumber = 5;
const result = input.filter(
    item => item != removeNumber
);

以上示例使用数组. prototype. filter 函数。 它会对所有数组项目进行循环, 并只返回符合箭头函数的项目。 因此, 旧数组保持不变, 而称为新数组的结果包含不等于5的所有项目。 您可以自己在网上测试它 。

您可以将数组. prototype. filter like this:

考虑考虑的考虑

守则质量

ARray. prototype. filter 是最容易读取的方法来删除这个例子中的数字, 它给错误留下很少的位置, 并使用联署材料的核心功能 。

为什么不设置数组. prototype.map?

ray. prototype.map 有时被视为用于此用途的数组. prototype. filter 的替代选项。 但不应使用它。 原因是数组. prototype. filter 概念上用来过滤符合箭头函数( 我们需要的精度)的项目, 而数组. prototype.map 则用来转换项目。 由于在对项目进行迭接时我们不修改项目, 正确的功能是数组. prototype. filter 。

支助支助支助支助支助支助支助支助支助支助支助支助支助支助支助支助支助支助

从今天(11.4.2022)起,94.08%的互联网用户浏览器支持阵列. prototype. filter。 所以一般地说, 使用是安全的。 但是, IE6 - 8 不支持它。 所以, 如果您的用法案例需要支持这些浏览器, Chris Ferdinanti 做了一个不错的多填。

业绩 业绩业绩 业绩业绩

Array. prototype. filter 对大多数使用的案例来说都是很好的。 但是, 如果您在寻找高级数据处理的性能改进, 您可以探索一些其他选项, 比如使用纯的选项。 另一个伟大的选项是重新思考您正在处理的阵列是否真的必须如此大。 这或许是一个信号, 即 JavaScript 应该从数据源获得一个减少的处理阵列 。

不同可能性的基准:https://jsben.ch/C5MXz

其他回答

您可以使用 JavaScript 的标准 __ proto__ 来定义此函数。例如,

让数据 = [;] 数据 .__proto__.remove = (n) { {数据 = 数据 : blockMap ((v) ) { { 返回 v ? v : [] n? v ; 数据 = [1, 2, 3] ; 数据 = [1, 2, 3] ; 数据.remove (2); 控制台.log(数据); / / [1,3] 数据 = [a', b', c'] ; 数据.remove ('b'); 控制台.log(数据); // [a, c]

在 ES6 中, Set 收藏提供了从数组中删除特定值的删除方法,然后根据分布运算符将 Set 收藏转换成数组。

函数 删除项目( list, val) { const set = new Set( list); set.delet( val); 设置. delete( val); 返回 [...set] ;} const 字母 = [“ A” , “ B” , “ C” , “ D” , “ E ” ; 控制台. log( deletetetetemmot( 字母, “ C ” ); / / [ “ A” , “ B” , “ D” , “ E ” 。

一种用ES6扩展操作器从数组中去除元素的永恒方式。

比方说你想删除4。

let array = [1,2,3,4,5]
const index = array.indexOf(4)
let new_array = [...array.slice(0,index), ...array.slice(index+1, array.length)]
console.log(new_array)
=> [1, 2, 3, 5]

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

数组. remove( 位置) ;

Array. prototype. remove = 函数 (pos) {此. splice(pos, 1);} var arr = ["a", "b", "c", "d", "e"]; arr. remove(2); // 移除"c" 控制台.log(ar);

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

array.erase(element);

Array. prototype. erase = 函数( el) { let p = this. indexof (el); // indexof use prettical equality () { this. spliice (p, 1);}} var ar ar = ["a", "b", "c", "d", "e"; arr.erase (c"); 控制台. log (a) ;

从字符串阵列中查找和删除一个特定的字符串:

var colors = ["red","blue","car","green"];
var carIndex = colors.indexOf("car"); // Get "car" index
// Remove car from the colors array
colors.splice(carIndex, 1); // colors = ["red", "blue", "green"]

资料来源:https://www.codegrepper.com/?search_term=remove+a+particulate+element+ from+array? 来源:https://www.codegrepper.com/?search_term=remove+a+partical+element+ from+array