如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
我知道答案已经很多了,但其中许多答案似乎都使问题复杂化了。这是一个简单的、循环性的方法,可以删除所有键的所有例子——在找不到索引之前自调键,直到找不到索引。是的,它只在浏览器中起作用。indexOf
,但它很简单,并且很容易被多填填充。
独立职能
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);
}
其他回答
定义:
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);
对我而言,越简单越好,2018年(2019年左右),我给你这个(近一点)单行话,回答最初的问题:
Array.prototype.remove = function (value) {
return this.filter(f => f != value)
}
有用的是,你可以用在咖喱的表达方式上,比如:
[1,2,3].remove(2).sort()
您在数组中有 1 到 9 个, 您想要删除 5 个 。 请使用以下代码 :
var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var newNumberArray = numberArray.filter(m => {
return m !== 5;
});
console.log("new Array, 5 removed", newNumberArray);
如果您想要多个值。例如:- 1,7,8
var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var newNumberArray = numberArray.filter(m => {
return (m !== 1) && (m !== 7) && (m !== 8);
});
console.log("new Array, 1,7 and 8 removed", newNumberArray);
如果您想要删除数组中的数组值。 例如 : [3,4,5]
var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var removebleArray = [3,4,5];
var newNumberArray = numberArray.filter(m => {
return !removebleArray.includes(m);
});
console.log("new Array, [3,4,5] removed", newNumberArray);
包括支持的浏览器链接链接.
一个非常天真的执行情况如下:
Array.prototype.remove = function(data) {
const dataIdx = this.indexOf(data)
if(dataIdx >= 0) {
this.splice(dataIdx ,1);
}
return this.length;
}
let a = [1,2,3];
// This will change arr a to [1, 3]
a.remove(2);
我从函数返回数组的长度以遵守其他方法,例如Array.prototype.push()
.
我喜欢这个单行道:
arr.includes(val) && arr.splice(arr.indexOf(val), 1)
null
或undefined
作为原型
// remove by value. return true if value found and removed, false otherwise
Array.prototype.remove = function(val)
{
return this.includes(val) && !!this.splice(this.indexOf(val), 1);
}
(是的,我读了所有其他的答案 却找不到一个结合的答案)includes
和splice
在同一行中。 )