如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
使用$.inAray, 以其价值删除一个元素:
$(document).ready(function(){
var arr = ["C#","Ruby","PHP","C","C++"];
var itemtoRemove = "PHP";
arr.splice($.inArray(itemtoRemove, arr),1);
});
其他回答
你的问题没有说明顺序或不同的价值是否是一项要求。
如果您不关心顺序, 并且容器中的值不会超过一次, 请使用“ Set ” 。 它会更快, 更简洁 。
var aSet = new Set();
aSet.add(1);
aSet.add(2);
aSet.add(3);
aSet.delete(2);
除了所有这些解决方案之外, 它也可以用阵列来完成. 减量...
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]
您可以为此创建一个原型。只需通过数组元素和您想要从数组元素中删除的值:
Array. prototype. removeTrounds = 函数( array, val) { { 数组. (raryTrounds, index) {如果 (rayTroups = val) { 数组. splice( index, 1);} 返回数组;} var DummyAray = [1、2、 3、4、 5、 6]; 控制台.log (DummyArray. removeTround (DummyArray, 3) );
一种用ES6扩展操作器从数组中去除元素的永恒方式。
比方说你想删除4。
let array = [1,2,3,4,5]
const index = array.indexOf(4)
let new_array = [...array.slice(0,index), ...array.slice(index+1, array.length)]
console.log(new_array)
=> [1, 2, 3, 5]
减少方法的利润如下:
(a) 需要按索引删除某一要素:
function remove(arr, index) {
return arr.reduce((prev, x, i) => prev.concat(i !== index ? [x] : []), []);
}
b) 需要删除元素值(int)的元素:
function remove(arr, value) {
return arr.reduce((prev, x, i) => prev.concat(x !== value ? [x] : []), []);
}
这样我们就可以返回一个新的阵列( 将会以酷酷的功能方式- 比使用推或组合要好得多) , 并删除元素 。