如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
最基本的解决办法是:
array.key = null;
其他回答
以下是几个方法使用 JavaScript 从数组中删除项目.
描述的所有方法不变换原始数组,而不是创造一个新的。
假设您有一个数组,而您想要删除位置中的项目i
.
一种方法是使用slice()
:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const i = 3
const filteredItems = items.slice(0, i).concat(items.slice(i+1, items.length))
console.log(filteredItems)
slice()
创建新数组, 使用它收到的索引 。 我们简单地创建一个新数组, 从开始到要删除的索引, 并且将另一个数组从我们删除的后第一个位置集中到数组的末尾 。
在这种情况下,一个好的选择是使用filter()
,它提供了更多宣示方针:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(item => item !== valueToRemove)
console.log(filteredItems)
此选项使用 ES6 箭头函数。 您可以使用传统函数支持旧的浏览器 :
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(function(item) {
return item !== valueToRemove
})
console.log(filteredItems)
或者你可以使用 Babel 将ES6代码转换回ES5, 使旧浏览器更容易消化, 而在您的代码中写入现代 JavaScript 。
如果不是单项,而是要删除许多项,会怎么样?
让我们找到最简单的解决方案
您可以在序列中创建函数并删除项目 :
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const removeItem = (items, i) =>
items.slice(0, i-1).concat(items.slice(i, items.length))
let filteredItems = removeItem(items, 3)
filteredItems = removeItem(filteredItems, 5)
//["a", "b", "c", "d"]
console.log(filteredItems)
您可以在回溯函数中搜索包含内容 :
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valuesToRemove = ['c', 'd']
const filteredItems = items.filter(item => !valuesToRemove.includes(item))
// ["a", "b", "e", "f"]
console.log(filteredItems)
splice()
(不与slice()
变换原始数组,并应避免。
(最初张贴在我的网站上)https://flaviocopes.com/how-to-remove-item-from-array/)
我喜欢这个单行道:
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
在同一行中。 )
let someArr = [...Array(99999).keys()]
console.time('filter')
someArr.filter(x => x !== 6666)
console.timeEnd('filter')
console.time('splice by indexOf')
someArr.splice(someArr.indexOf(6666), 1)
console.timeEnd('splice by indexOf')
在我的机器上splice
更快。这有道理,因为splice
仅编辑现有的数组,而filter
创建新数组。
尽管如此,filter
逻辑上更清洁(容易阅读),更适合使用不可改变状态的编码风格。所以由你决定是否进行这种权衡决定。
很简单,只要做:
var arr = [1,2,4,5];
arr.splice(arr.indexOf(5), 1);
console.log(arr); // [1,2,4];
(function removeFromArrayPolyfill() {
if (window.Array.prototype.remove) return;
Array.prototype.remove = function (value) {
if (!this.length || !value) return;
const indexOfValue = this.indexOf(value);
if (indexOfValue >= 0) {
this.splice(indexOfValue, 1);
}
};
})();
// testing polyfill
const nums = [10, 20, 30];
nums.remove(20);
console.log(nums);//[10,30]