如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
除了所有这些解决方案之外, 它也可以用阵列来完成. 减量...
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]
其他回答
如果您在数组中有复杂的对象, 您可以使用过滤器 。 在 $. in Array 或 tray. splice 不容易使用的情况下 。 特别是如果对象在数组中可能是浅的 。
例如,如果您有一个带有 Id 字段的对象,而您想要从数组中删除该对象:
this.array = this.array.filter(function(element, i) {
return element.id !== idToRemove;
});
您可以使用标准__proto__
JavaScript 和定义此函数。例如,
let data = [];
data.__proto__.remove = (n) => { data = data.flatMap((v) => { return v !== n ? v : []; }) };
data = [1, 2, 3];
data.remove(2);
console.log(data); // [1,3]
data = ['a','b','c'];
data.remove('b');
console.log(data); // [a,c]
检查一下这个代码 每个代码都有效主浏览器.
remove_item = function(arr, value) {
var b = '';
for (b in arr) {
if (arr[b] === value) {
arr.splice(b, 1);
break;
}
}
return arr;
};
var array = [1,3,5,6,5,9,5,3,55]
var res = remove_item(array,5);
console.log(res)
从字符串阵列中查找和删除一个特定的字符串:
var colors = ["red","blue","car","green"];
var carIndex = colors.indexOf("car"); // Get "car" index
// Remove car from the colors array
colors.splice(carIndex, 1); // colors = ["red", "blue", "green"]
资料来源:https://www.codegrepper.com/?search_term=remove+a+particular+element+from+array
使用欧 6扩展操作员 。
比方说你想删除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]