如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
Array.prototype.removeItem = function(a) {
for (i = 0; i < this.length; i++) {
if (this[i] == a) {
for (i2 = i; i2 < this.length - 1; i2++) {
this[i2] = this[i2 + 1];
}
this.length = this.length - 1
return;
}
}
}
var recentMovies = ['Iron Man', 'Batman', 'Superman', 'Spiderman'];
recentMovies.removeItem('Superman');
其他回答
从数组中删除一个特定元素/字符串可在单班条中进行:
theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1);
此处:
阵列:要从
将字符串从矩阵中移除:要删除的字符串,而1是要删除的元素数量。
注 注 注 注 注注:如果“字符串要从阵列中移除”不位于数组中,这将删除数组的最后一个元素。
在移除该元素之前先检查该元素是否存在于您的阵列中, 总是很好的做法 。
if (theArray.indexOf("stringToRemoveFromArray") >= 0){
theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1);
}
取决于客户电脑上是否有新版或旧版的剪贴条:
var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');
或
var array = ['1','2','3','4','5','6'];
var newArray = array.filter(function(item){ return item !== '3' });
“ 3” 是您想要从数组中删除的值。 然后, 数组将变成 :['1','2','4','5','6']
最干净的:
var arr = ['1','2','3'];
arr = arr.filter(e => e !== '3');
console.warn(arr);
这也将删除重复(如果有的话)。
我喜欢这个单行道:
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
在同一行中。 )
使用使用jj 查询. grep ():
var y = [1, 2, 3, 9, 4]
var removeItem = 9;
y = jQuery.grep(y, function(value) {
return value != removeItem;
});
console.log(y)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
如果您想要[...].remove( el)- 类似语法,与其他编程语言一样, 然后你可以添加这个代码 :
// Add remove method to Array prototype
Array.prototype.remove = function(value, count=this.length) {
while(count > 0 && this.includes(value)) {
this.splice(this.indexOf(value), 1);
count--;
}
return this;
}
// Original array
const arr = [1,2,2,3,2,5,6,7];
// Remove all 2s from array
arr.remove(2); // [1,3,5,6,7]
// Remove one 2 from beginning of array
arr.remove(2, 1); // [1,2,3,2,5,6,7]
// Remove two 2s from beginning of array
arr.remove(2, 2); // [1,3,2,5,6,7]
您可以根据您的需求操控该方法 。