如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
我设定了一个函数:
function pop(valuetoremove, myarray) {
var indexofmyvalue = myarray.indexOf(valuetoremove);
myarray.splice(indexofmyvalue, 1);
}
并用它这样:
pop(valuetoremove, myarray);
其他回答
通过传递其值来删除项目 --
const remove=(value)=>{
myArray = myArray.filter(element=>element !=value);
}
将项目通过索引编号删除 -
const removeFrom=(index)=>{
myArray = myArray.filter((_, i)=>{
return i!==index
})
}
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;
}
更现代一点ECMAScript 2015(原称和谐或ES6)方法。
const items = [1, 2, 3, 4];
const index = 2;
然后:
items.filter((x, i) => i !== index);
弹出 :
[1, 2, 4]
如果你想删除几个项目, 我发现这是最容易的:
const oldArray = [1, 2, 3, 4, 5]
const removeItems = [1, 3, 5]
const newArray = oldArray.filter((value) => {
return !removeItems.includes(value)
})
console.log(newArray)
产出:
[2, 4]
const arr = [1, 2, 3, 4, 5]
console.log(arr) // [ 1, 2, 3, 4, 5 ]
假设你想从Arr删除3号
const newArr = arr.filter(w => w !==3)
console.log(newArr) // [ 1, 2, 4, 5 ]