如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
尝试使用过滤器方法使用此代码, 您可以从数组中删除任何特定项 。
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function removeItem(arr, value) {
return arr.filter(function (ele) {
return ele !== value;
});
}
console.log(removeItem(arr, 6));
其他回答
如果您必须支持旧版的 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/
使用 jQuery. grep () :
var y = [1, 2, 3, 9, 4] var 删除项目 = 9; y = jQuery.grep(y, 函数(价值) {返回值 = demotephle; }; 控制台. log(y) <Src=" https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"\\/pict>
这取决于你是否想保持一个空位。
如果您想要一个空位 :
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 , 如果找不到的话 。
我设定了一个函数:
function pop(valuetoremove, myarray) {
var indexofmyvalue = myarray.indexOf(valuetoremove);
myarray.splice(indexofmyvalue, 1);
}
并用它这样:
pop(valuetoremove, myarray);
var 数组 = [2, 5, 9]; var res = 数组.spliice( array. findindIndex( x x x = = = 5) 1; 控制台. log( res) (sres)
使用 Array. findindindex, 我们可以减少代码行数。
开发者.mozilla.org