我有一个数字数组,我正在使用它.push()向其中添加元素的方法。 . p: W1 P9 H6 \, J" ]从数组中删除特定元素有没有简单的方法?6 F/ x* v9 J( x/ l5 I- Q( i
我在寻找类似的东西:& Y: `3 w% s+ f9 U& A, }7 T( }5 r
array.remove(number); 2 P* [* k, l6 O6 U2 d! T
我必须使用核心JavaScript。框架不允许使用。- o2 ^' P9 W# ]6 R; A z
9 C; M) P+ \1 o2 o 解决方案: # e, ^4 m) ^. b% U& Y
使用 查找index要删除的数组元素indexOf,然后用 删除索引splice。 4 y0 |- ~, r* g5 a) a" Isplice() 通过删除现有元素和/或添加新元素来改变数组的内容。% ~# y% K% a+ S
const array = [2,5,9];console.log(array);const index = array.indexOf(5);if (index > -1) { array.splice(index,1);}// array = [2,9]console.log(array); 2 j+ C& C) l) D. M( g
function removeItemOnce(arr,value) { var index = arr.indexOf(value); if (index > -1) { arr.splice(index,1); } return arr;}function removeItemAll(arr,value) { var i = 0; while (i 在 TypeScript 通过类型参数,这些函数可以保持类型安全:[code]function removeItem(arr: Array,value: T): Array { const index = arr.indexOf(value); if (index > -1) { arr.splice(index,1); } return arr;} & E! Y6 Q- D$ M