如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
定义:
function RemoveEmptyItems(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) if (arr[i] != null && arr[i].length > 0) result.push(arr[i]);
return result;
}
用法 :
var arr = [1,2,3, "", null, 444];
arr = RemoveEmptyItems(arr);
console.log(arr);
其他回答
OK,例如,您有下面的数组:
var num = [1, 2, 3, 4, 5];
我们想要删除第4号, 你可以简单地使用下面的代码:
num.splice(num.indexOf(4), 1); // num will be [1, 2, 3, 5];
如果您正在重复使用此函数,请写入一个可重复使用的函数,该函数将附加在本地数组函数上,如下文所示:
Array.prototype.remove = Array.prototype.remove || function(x) {
const i = this.indexOf(x);
if(i===-1)
return;
this.splice(i, 1); // num.remove(5) === [1, 2, 3];
}
但如果您有下面的数组, 而不是数组中的几个 [5] 呢?
var num = [5, 6, 5, 4, 5, 1, 5];
我们需要一个循环来检查它们, 但是一个更容易和更有效的方法是使用内置的 JavaScript 函数, 所以我们写一个函数, 使用下面这样的过滤器 :
const _removeValue = (arr, x) => arr.filter(n => n!==x);
//_removeValue([1, 2, 3, 4, 5, 5, 6, 5], 5) // Return [1, 2, 3, 4, 6]
还有第三方图书馆,如Lodash 或Goint, 也帮助你这样做。更多信息,请参看 Lodash _. pull,_. pullAt 或_。
Array. prototype. removeByValue = 函数( val) {, 对于 (var i = 0; i < this. long; i++) { 如果 (i) val) { this. splice (i, 1); i- ; } 返回此 ;} var falts = [apple, 'banana', 'carrot', 'orange' ] ; falves.remove ByValue ('banana'); 礼服. log (fruts); / / - > [apple, 'carrot', 'orange' ]
您可以使用ES6. 例如,在此情况下删除值“ 3” :
var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');
console.log(newArray);
产出:
["1", "2", "4", "5", "6"]
这取决于你是否想保持一个空位。
如果您想要一个空位 :
array[index] = undefined;
如果你不想空空的位子:
//To keep the original:
//oldArray = [...array];
//This modifies the 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 , 如果找不到的话 。
一个非常天真的执行情况如下:
Array. prototype. remove = 函数( data) { const dataIdx = this. indexof( data) if (dataIdx { { { 0) { this.spice( dataIdx, 1) { 返回此. 长度;} } 允许 a = [1, 2,3] ; / / 这将将 Arr a 改为 [1, 3] a. remove(2) ;
我从函数返回数组的长度以遵守其他方法, 如 Array. prototype. push () 。