如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
非就地解决办法
arr.slice(0,i).concat(arr.slice(i+1));
let arr = [10, 20, 30, 40, 50]
let i = 2 ; // position to remove (starting from 0)
let r = arr.slice(0,i).concat(arr.slice(i+1));
console.log(r);
其他回答
var arr =[1,2,3,4,5];
arr.splice(0,1)
console.log(arr)
产出[2、3、4、5];
此函数从特定位置的数组中删除元素。
array.remove(position);
Array.prototype.remove = function (pos) {
this.splice(pos, 1);
}
var arr = ["a", "b", "c", "d", "e"];
arr.remove(2); // remove "c"
console.log(arr);
如果您不知道要删除的项目的位置, 请使用这个 :
array.erase(element);
Array.prototype.erase = function(el) {
let p = this.indexOf(el); // indexOf use strict equality (===)
if(p != -1) {
this.splice(p, 1);
}
}
var arr = ["a", "b", "c", "d", "e"];
arr.erase("c");
console.log(arr);
除了所有这些解决方案之外, 它也可以用阵列来完成. 减量...
const removeItem =
idx =>
arr =>
arr.reduce((acc, a, i) => idx === i ? acc : acc.concat(a), [])
const array = [1, 2, 3]
const index = 1
const newArray = removeItem(index)(array)
console.log(newArray) // logs the following array to the console : [1, 3]
...或者一个循环函数(诚实地说不是那么优雅...也许有人有更好的循环解决方案? ? )...
const removeItemPrep =
acc =>
i =>
idx =>
arr =>
// If the index equals i, just feed in the unchanged accumulator(acc) else...
i === idx ? removeItemPrep(acc)(i + 1)(idx)(arr) :
// If the array length + 1 of the accumulator is smaller than the array length of the original array concatenate the array element at index i else...
acc.length + 1 < arr.length ? removeItemPrep(acc.concat(arr[i]))(i + 1)(idx)(arr) :
// return the accumulator
acc
const removeItem = removeItemPrep([])(0)
const array = [1, 2, 3]
const index = 1
const newArray = removeItem(index)(array)
console.log(newArray) // logs the following array to the console : [1, 3]
我还有一个从阵列中移除的好办法:
var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
最干净的:
var arr = ['1','2','3'];
arr = arr.filter(e => e !== '3');
console.warn(arr);
这也将删除重复(如果有的话)。