如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
您可以对每个数组项进行循环, 如果在您的数组中存在的话, 可以复制并连接它 。
function destroy(arr, val) {
for (var i = 0; i < arr.length; i++) if (arr[i] === val) arr.splice(i, 1);
return arr;
}
其他回答
您可以在 JavaScript 以多种方式完成此任务
如果您知道该值的索引 : 您可以在此情况下使用 spolice var arr = [1, 2, 3,4] / / / / 假设我们有该索引, 来源于某些 API let index = 2; // spolice 是一种破坏性的方法, 并修改原始数组 arr. spice (2, 1) 。 如果您没有该索引, 并且只有该值 : 您可以在此情况下使用过滤器 / / let's remove '2', 例如 arr = arr. filter (( 值) 返回值 $ ( = 2); }
您可以使用复数来从数组中删除对象或值。
让我们考虑一个长度为5的行距, 值为10,20,30,40,50, 我想从中去掉30的值。
var 数组 = [10,20,30,40,50];如果 (数组. indexof(30) > -1) {数组.spice( 数组. indexof(30), 1);} 控制台. log( 数组); / / [10,20, 40,50]
您可以扩展数组对象以定义自定义的删除函数如下:
let let = [1, 2,4,4,4,5,5,45,9;] 数.delete = 函数(价值) { var indexof Target = this.indexof (value) =.indexof(value) = this.if(indexoftaget = = = = = = = = = = y= = y,4,4,4,5,4,459; 数. 数.delet = 函数(val = val indexof Talget = this. indexeof(valent) = = = = = indexget =.indexof = = =. { = indexexuf(val =) { = = indexete = = / / / imme eleteletelete (1) // / / / / 预期输出= / / / tradestrayf delett 删除 2,4,4,4,4,4,4,5,5,5,4,4,5,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,9/ /
此函数从特定位置的数组中删除元素。
数组. 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) ;
弹出 - 从阵列变化的结尾处删除 - 从阵列复件的开头处删除 - 从特定的阵列索引过滤器中删除 - 允许您程序化地从阵列中删除元素