如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
您可以使用
Array.splice(index);
其他回答
这取决于你是否想保持一个空位。
如果您想要一个空位 :
array[index] = undefined;
如果你不想空空的位子:
保留原件:
oldArray = [...array];
这将修改数组。
array.splice(index, 1);
如果您需要该项的值, 您可以保存返回的数组元素 :
var value = array.splice(index, 1)[0];
如果您想要在数组的两端删除, 您可以在最后一个或数组中使用数组. pop () 。 第一个或数组中可以使用数组. translate. pop () 。 translate () toft () for first one (两者都返回项目值 ) 。
如果您不知道项目的索引, 您可以使用数组。 indexof( 项目) 来获取它( 在 if( ) 中获得一个项, 或者在 a while( ) 中获取全部项 ) 。 数组。 indexof( 项目) 返回索引, 或 - 1 , 如果找不到的话 。
此函数从特定位置的数组中删除元素。
数组. remove( 位置) ;
Array. prototype. remove = 函数 (pos) {此. splice(pos, 1);} var arr = ["a", "b", "c", "d", "e"]; arr. remove(2); // 移除"c" 控制台.log(ar);
如果您不知道要删除的项目的位置, 请使用这个 :
array.erase(element);
Array. prototype. erase = 函数( el) { let p = this. indexof (el); // indexof use prettical equality () { this. spliice (p, 1);}} var ar ar = ["a", "b", "c", "d", "e"; arr.erase (c"); 控制台. log (a) ;
除了所有这些解决方案之外, 它也可以用阵列来完成. 减量...
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]
这是我的简单的代码, 用来使用 复数法删除数组中的具体数据。 复数法将给两个参数。 第一个参数是起始数, 第二个参数是删除Count。 第二个参数用于删除从第一个参数值开始的某个元素 。
let arr = [1, 3, 5, 6, 9];
arr.splice(0, 2);
console.log(arr);
正在删除带有索引和相交点的值 !
function removeArrValue(arr,value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}