如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
我设定了一个函数:
function pop(valuetoremove, myarray) {
var indexofmyvalue = myarray.indexOf(valuetoremove);
myarray.splice(indexofmyvalue, 1);
}
并用它这样:
pop(valuetoremove, myarray);
其他回答
删除单个元素
function removeSingle(array, element) {
const index = array.indexOf(element)
if (index >= 0) {
array.splice(index, 1)
}
}
删除多个元素, 位置内
这对于确保算法在O(N)时间运行更为复杂。
function removeAll(array, element) {
let newLength = 0
for (const elem of array) {
if (elem !== number) {
array[newLength++] = elem
}
}
array.length = newLength
}
删除多个元素,创建新对象
array.filter(elem => elem !== number)
如果您必须支持旧版的 Internet Explorer , 我建议使用以下多个填充( 注意: 这不是一个框架 ) 。 这是所有现代阵列方法( JavaScript 1. 8. 5/ ECMAScript 5 Array Extras) 的100%的后向兼容替换, 用于 Internet Explorer 6+, Firefox 1. 5+, Chrome, Safari, & Opera 。
https://github.com/pludude/array-generics https://github.com/pludude/ array-generics https://github.com/plusdude/arary-generics/servics/
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)
更现代的ECMAScript 2015(原称和谐或ES6)方法。
const items = [1, 2, 3, 4];
const index = 2;
然后:
items.filter((x, i) => i !== index);
弹出 :
[1, 2, 4]
您可以使用 Babel 和多填充服务,以确保浏览器之间有很好的支持。
这取决于你是否想保持一个空位。
如果您想要一个空位 :
array[index] = undefined;
如果你不想空空的位子:
保留原件:
oldArray = [...array];
这将修改数组。
array.splice(index, 1);
如果您需要该项的值, 您可以保存返回的数组元素 :
var value = array.splice(index, 1)[0];
如果您想要在数组的两端删除, 您可以在最后一个或数组中使用数组. pop () 。 第一个或数组中可以使用数组. translate. pop () 。 translate () toft () for first one (两者都返回项目值 ) 。
如果您不知道项目的索引, 您可以使用数组。 indexof( 项目) 来获取它( 在 if( ) 中获得一个项, 或者在 a while( ) 中获取全部项 ) 。 数组。 indexof( 项目) 返回索引, 或 - 1 , 如果找不到的话 。