如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
调
2021年更新
您的问题是如何从数组中删除一个特定项目。 您在具体项目中指的是一个数字, 例如 。 从数组中删除数字 5 。 据我了解, 您正在寻找类似 :
// PSEUDOCODE, SCROLL FOR COPY-PASTE CODE
[1,2,3,4,5,6,8,5].remove(5) // result: [1,2,3,4,6,8]
至于2021年,实现该目标的最佳途径是使用数组过滤功能:
const input = [1,2,3,4,5,6,8,5];
const removeNumber = 5;
const result = input.filter(
item => item != removeNumber
);
以上示例使用数组. prototype. filter 函数。 它会对所有数组项目进行循环, 并只返回符合箭头函数的项目。 因此, 旧数组保持不变, 而称为新数组的结果包含不等于5的所有项目。 您可以自己在网上测试它 。
您可以将数组. prototype. filter like this:
调
考虑考虑的考虑
守则质量
ARray. prototype. filter 是最容易读取的方法来删除这个例子中的数字, 它给错误留下很少的位置, 并使用联署材料的核心功能 。
为什么不设置数组. prototype.map?
ray. prototype.map 有时被视为用于此用途的数组. prototype. filter 的替代选项。 但不应使用它。 原因是数组. prototype. filter 概念上用来过滤符合箭头函数( 我们需要的精度)的项目, 而数组. prototype.map 则用来转换项目。 由于在对项目进行迭接时我们不修改项目, 正确的功能是数组. prototype. filter 。
支助支助支助支助支助支助支助支助支助支助支助支助支助支助支助支助支助支助
从今天(11.4.2022)起,94.08%的互联网用户浏览器支持阵列. prototype. filter。 所以一般地说, 使用是安全的。 但是, IE6 - 8 不支持它。 所以, 如果您的用法案例需要支持这些浏览器, Chris Ferdinanti 做了一个不错的多填。
业绩 业绩业绩 业绩业绩
Array. prototype. filter 对大多数使用的案例来说都是很好的。 但是, 如果您在寻找高级数据处理的性能改进, 您可以探索一些其他选项, 比如使用纯的选项。 另一个伟大的选项是重新思考您正在处理的阵列是否真的必须如此大。 这或许是一个信号, 即 JavaScript 应该从数据源获得一个减少的处理阵列 。
不同可能性的基准:https://jsben.ch/C5MXz
其他回答
Array.prototype.remove = function(start, end) {
var n = this.slice((end || start) + 1 || this.length);
return this.length = start < 0 ? this.length + start : start,
this.push.apply(this, n)
}
开始和结束可以是负的。 在这种情况下, 它们会从数组的末尾计数 。
如果只指定开始,则只删除一个元素。
函数返回新数组长度。
z = [0,1,2,3,4,5,6,7,8,9];
newlength = z.remove(2,6);
(8) [0, 1, 7, 8, 9]
z=[0,1,2,3,4,5,6,7,8,9];
newlength = z.remove(-4,-2);
(7) [0, 1, 2, 3, 4, 5, 9]
z=[0,1,2,3,4,5,6,7,8,9];
newlength = z.remove(3,-2);
(4) [0, 1, 2, 9]
(function removeFromArrayPolyfill() {
if (window.Array.prototype.remove) return;
Array.prototype.remove = function (value) {
if (!this.length || !value) return;
const indexOfValue = this.indexOf(value);
if (indexOfValue >= 0) {
this.splice(indexOfValue, 1);
}
};
})();
// testing polyfill
const nums = [10, 20, 30];
nums.remove(20);
console.log(nums);//[10,30]
我知道已经有很多答案了, 但其中许多答案似乎都使问题复杂化了。 这是一个简单的、循环的删除所有关键实例的方法- 在找不到索引之前自呼自用。 是的, 它只在有索引的浏览器中起作用, 但是它很简单, 并且很容易被多填 。
独立职能
function removeAll(array, key){
var index = array.indexOf(key);
if(index === -1) return;
array.splice(index, 1);
removeAll(array,key);
}
原型方法
Array.prototype.removeAll = function(key){
var index = this.indexOf(key);
if(index === -1) return;
this.splice(index, 1);
this.removeAll(key);
}
我不知道你如何期待阵列.remove( int) 的行为。 我可以想到三种可能性, 你可能会想要。
要删除索引 i 中的数组元素:
array.splice(i, 1);
如果您想要从数组中删除带有数值数的每个元素 :
for (var i = array.length - 1; i >= 0; i--) {
if (array[i] === number) {
array.splice(i, 1);
}
}
如果您只想在索引 I 中使元素不再存在, 但是您不想让其它元素的索引改变 :
delete array[i];
正在删除带有索引和相交点的值 !
function removeArrValue(arr,value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}