如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
如果您在数组中有复杂的对象, 您可以使用过滤器 。 在 $. in Array 或 tray. splice 不容易使用的情况下 。 特别是如果对象在数组中可能是浅的 。
例如,如果您有一个带有 Id 字段的对象,而您想要从数组中删除该对象:
this.array = this.array.filter(function(element, i) {
return element.id !== idToRemove;
});
其他回答
ES6且无突变:(2016年10月)
const removeByIndex = (list, index) =>
[
...list.slice(0, index),
...list.slice(index + 1)
];
output = removeByIndex([33,22,11,44],1) //=> [33,11,44]
console.log(output)
从数组中删除一个特定元素/字符串可在单班条中进行:
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']
如果您使用现代浏览器, 您可以使用. 过滤器 。
Array.prototype.remove = function(x){
return this.filter(function(v){
return v !== x;
});
};
var a = ["a","b","c"];
var b = a.remove('a');
我刚刚创建了一个多填充Array.prototype
通过Object.defineProperty
以删除数组中一个想要的元素,而不会在稍后通过for .. in ..
if (!Array.prototype.remove) {
// Object.definedProperty is used here to avoid problems when iterating with "for .. in .." in Arrays
// https://stackoverflow.com/questions/948358/adding-custom-functions-into-array-prototype
Object.defineProperty(Array.prototype, 'remove', {
value: function () {
if (this == null) {
throw new TypeError('Array.prototype.remove called on null or undefined')
}
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] === 'object') {
if (Object.keys(arguments[i]).length > 1) {
throw new Error('This method does not support more than one key:value pair per object on the arguments')
}
var keyToCompare = Object.keys(arguments[i])[0]
for (var j = 0; j < this.length; j++) {
if (this[j][keyToCompare] === arguments[i][keyToCompare]) {
this.splice(j, 1)
break
}
}
} else {
var index = this.indexOf(arguments[i])
if (index !== -1) {
this.splice(index, 1)
}
}
}
return this
}
})
} else {
var errorMessage = 'DANGER ALERT! Array.prototype.remove has already been defined on this browser. '
errorMessage += 'This may lead to unwanted results when remove() is executed.'
console.log(errorMessage)
}
删除整数值
var a = [1, 2, 3]
a.remove(2)
a // Output => [1, 3]
删除字符串值
var a = ['a', 'ab', 'abc']
a.remove('abc')
a // Output => ['a', 'ab']
删除布尔值
var a = [true, false, true]
a.remove(false)
a // Output => [true, true]
也可以通过此方法从数组中移除对象Array.prototype.remove
方法。只需指定key => value
of the Object
您想要删除。
删除对象值
var a = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 3, b: 2}]
a.remove({a: 1})
a // Output => [{a: 2, b: 2}, {a: 3, b: 2}]