如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
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 或_。
其他回答
删除一个数值,使用松放比较,不突变原始数组ES6
/**
* Removes one instance of `value` from `array`, without mutating the original array. Uses loose comparison.
*
* @param {Array} array Array to remove value from
* @param {*} value Value to remove
* @returns {Array} Array with `value` removed
*/
export function arrayRemove(array, value) {
for(let i=0; i<array.length; ++i) {
if(array[i] == value) {
let copy = [...array];
copy.splice(i, 1);
return copy;
}
}
return array;
}
使用数组过滤法 :
let array = [1, 2, 3, 4, 511, 34, 511, 78, 88];
let value = 511;
array = array.filter(element => element !== value);
console.log(array)
从带有数组元素的阵列列表中获取阵列和索引 从使用地图toint () 和 Toarray () 方法的阵列新阵列中删除 使用删除 () 方法删除具体索引元素 返回格式化的阵列
很简单,只要做:
var arr = [1,2,4,5];
arr.splice(arr.indexOf(5), 1);
console.log(arr); // [1,2,4];
您可以简单地将删除函数添加到数组原体Type
类似的东西 :
Array.prototype.remove = function(value) {
return this.filter(item => item !== value)
}
Array. prototype. remove = 函数( 值) { 返回此功能 。 filter (项目 项 ! === value) } 让阵列 = [10, 15,20] 结果 = 数组. remove(10) 控制台.log (结果) (结果)