如何从数组中删除一个特定值? 类似 :

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);

其他回答

从数组中删除一个特定元素/字符串可在单班条中进行:

theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1);

此处:

阵列:要从

将字符串从矩阵中移除:要删除的字符串,而1是要删除的元素数量。

注 注 注 注 注注:如果“字符串要从阵列中移除”不位于数组中,这将删除数组的最后一个元素。

在移除该元素之前先检查该元素是否存在于您的阵列中, 总是很好的做法 。

if (theArray.indexOf("stringToRemoveFromArray") >= 0){
   theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1);
}

取决于客户电脑上是否有新版或旧版的剪贴条:

var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');

var array = ['1','2','3','4','5','6'];
var newArray = array.filter(function(item){ return item !== '3' });

“ 3” 是您想要从数组中删除的值。 然后, 数组将变成 :['1','2','4','5','6']

尝试使用此代码filter方法,您可以从数组中删除任何特定项。

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function removeItem(arr, value) {
  return arr.filter(function (ele) {
    return ele !== value;
  });
}
console.log(removeItem(arr, 6));

使用欧 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]
[2,3,5].filter(i => ![5].includes(i))
  1. 获取数组和索引
  2. 从带有数组元素的数组列表
  3. 使用remove()方法
  4. 从使用的新数组列表的阵列数组中maptoint()toarray()方法
  5. 返回格式化的数组