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

array.remove(value);

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


当前回答

我测试了复数和过滤器 看哪个更快:

let someArr = [... Array(999999). keys ()] 控制台.time(“ filter” ) someArr. filter(x x = = = = = 666666) 控制台.timeEnd(“ filter ” ) 控制台.time(“ splice by indexof ” ) someArr. splice( some Arr. indexof( 6666), 1) 控制台.timeEnd( “ splice by indexof ” )

在我的机器上, 复数会更快。 这有道理, 因为复数只编辑一个已有的数组, 而过滤器会创建一个新的数组 。

因此,过滤器在逻辑上是更清洁的(更容易阅读),并且更适合使用不可改变状态的编码风格。因此,由你来决定你是否想做出这种权衡。

其他回答

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

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

. filter () 方法映射为完整的数组, 当我返回真实状态时, 它会将当前项目推到过滤的数组。 在此过滤器中读取更多 。

ES6且无突变:(2016年10月)

const removeByIndex = (list, index) => [ ...list.slice(0, index), ...list.slice(index + 1) ]; output = removeByIndex([33,22,11,44],1) //=> [33,11,44] console.log(output)

从数组中删除一个特定元素/字符串可在单班条中进行:

theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1);

此处:

阵列:要从

将字符串从矩阵中删除:您想要删除的字符串, 1 是您想要删除的元素数量 。

注意 : 如果“ 字符串要从阵列中移除” 不位于数组中, 这将删除数组中的最后元素 。

在移除该元素之前先检查该元素是否存在于您的阵列中, 总是很好的做法 。

if (theArray.indexOf("stringToRemoveFromArray") >= 0){
   theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1);
}

取决于客户电脑上是否有新版或旧版的剪贴条:

var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');

var array = ['1','2','3','4','5','6'];
var newArray = array.filter(function(item){ return item !== '3' });

“ 3” 是您想要从数组中删除的值。 数组会变成 : [“ 1 ” , “ 2 ” , “ 4 ” , “ 5 ” , “ 6 ”

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

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

然后:

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

弹出 :

[1, 2, 4]

您可以使用 Babel 和多填充服务,以确保浏览器之间有很好的支持。

删除上次的元素

arrName.pop();

删除第一个元素

arrName.shift();

从中间删除

arrName.splice(starting index, number of element you wnt to delete);

Example: arrName.splice(1, 1);

删除最后一个元素

arrName.splice(-1);

使用数组索引编号删除

 delete arrName[1];