如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
我对JavaScript很新,需要这个功能。我只是写了这个:
function removeFromArray(array, item, index) {
while((index = array.indexOf(item)) > -1) {
array.splice(index, 1);
}
}
然后,当我想使用它:
//Set-up some dummy data
var dummyObj = {name:"meow"};
var dummyArray = [dummyObj, "item1", "item1", "item2"];
//Remove the dummy data
removeFromArray(dummyArray, dummyObj);
removeFromArray(dummyArray, "item2");
输出 - 如预期的那样。 [“项目1”、“项目1”]
你可能跟我有不同的需要,所以你可以轻易地修改,以适合他们。我希望这能帮助别人。
其他回答
你可以绕过每个array
- 分项目和项目splice
如果它存在于你的体内array
.
function destroy(arr, val) {
for (var i = 0; i < arr.length; i++) if (arr[i] === val) arr.splice(i, 1);
return arr;
}
我刚刚创建了一个多填充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}]
2017-05-08
大多数给定的回答都用于严格的比较, 意思是两个对象在内存( 或原始类型) 中引用完全相同的对象, 但通常您想要从具有一定值的数组中删除一个非原始对象。 例如, 如果您给服务器打电话, 并想要对照本地对象检查已检索到的对象 。
const a = {'field': 2} // Non-primitive object
const b = {'field': 2} // Non-primitive object with same value
const c = a // Non-primitive object that reference the same object as "a"
assert(a !== b) // Don't reference the same item, but have same value
assert(a === c) // Do reference the same item, and have same value (naturally)
//Note: there are many alternative implementations for valuesAreEqual
function valuesAreEqual (x, y) {
return JSON.stringify(x) === JSON.stringify(y)
}
//filter will delete false values
//Thus, we want to return "false" if the item
// we want to delete is equal to the item in the array
function removeFromArray(arr, toDelete){
return arr.filter(target => {return !valuesAreEqual(toDelete, target)})
}
const exampleArray = [a, b, b, c, a, {'field': 2}, {'field': 90}];
const resultArray = removeFromArray(exampleArray, a);
//resultArray = [{'field':90}]
数值AreEqual有替代/更快的操作,但这样可以操作。如果您有特定的字段要检查,也可以使用自定义的比较器(例如,有些已检索的 UUID 相对于本地的 UUID ) 。
2. 还注意到这是一个功能操作,意即它不改变原始阵列。
Vanilla JavaScript(ES5.1) - (ES5.1) -已经到位版本版本
浏览器支持 :因特网探索者 9或以后(或以后(详细浏览器支持)
/**
* Removes all occurences of the item from the array.
*
* Modifies the array “in place”, i.e. the array passed as an argument
* is modified as opposed to creating a new array. Also returns the modified
* array for your convenience.
*/
function removeInPlace(array, item) {
var foundIndex, fromIndex;
// Look for the item (the item can have multiple indices)
fromIndex = array.length - 1;
foundIndex = array.lastIndexOf(item, fromIndex);
while (foundIndex !== -1) {
// Remove the item (in place)
array.splice(foundIndex, 1);
// Bookkeeping
fromIndex = foundIndex - 1;
foundIndex = array.lastIndexOf(item, fromIndex);
}
// Return the modified array
return array;
}
Vanilla JavaScript(ES5.1) - (ES5.1) -不可变版本版本
浏览器支持: 与原版的香草 JavaScript 相同
/**
* Removes all occurences of the item from the array.
*
* Returns a new array with all the items of the original array except
* the specified item.
*/
function remove(array, item) {
var arrayCopy;
arrayCopy = array.slice();
return removeInPlace(arrayCopy, item);
}
香草ES6 -不可变版本版本
浏览器支持: Chrome 46, 边缘 12, Firefox 16, Opera 37, Safari 8 ()详细浏览器支持)
/**
* Removes all occurences of the item from the array.
*
* Returns a new array with all the items of the original array except
* the specified item.
*/
function remove(array, item) {
// Copy the array
array = [...array];
// Look for the item (the item can have multiple indices)
let fromIndex = array.length - 1;
let foundIndex = array.lastIndexOf(item, fromIndex);
while (foundIndex !== -1) {
// Remove the item by generating a new array without it
array = [
...array.slice(0, foundIndex),
...array.slice(foundIndex + 1),
];
// Bookkeeping
fromIndex = foundIndex - 1;
foundIndex = array.lastIndexOf(item, fromIndex)
}
// Return the new array
return array;
}
使用使用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>