如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
使用 indexof, 可以用 spolice 从数组中找到一个特定的数字索引, 从数组中删除一个特定的索引 。
const 数组 = [1,2,3,4,5,6,6,7,7,8,9,0]; const 指数 = 数组.indexof(5); /// 找到具体数字的索引 if( index != -1) { 数组.splice( index, 1); // 使用 index world. log( 数组) 删除数字 ;
删除全部事件 。 @ info: whatsthis
数组数组 = [1、2、3、4、4、5、1、7、8、9、9、2、3、4、5、6] 数组 = 数组. filter( number_@ number!=5); 控制台. log( 数组) ;
使用 join 和 share let 数组 = [1、2、3、4、5、1、7、8、9、2、3、4、5、6] 数组 = 数组 。 来自 (array.join ("-" -").split ("-5 -").join (" -").split ("-").split ("-"), number) 控制台.log (ray) 的 数组 。
其他回答
Array.prototype.remove = function(start, end) {
var n = this.slice((end || start) + 1 || this.length);
return this.length = start < 0 ? this.length + start : start,
this.push.apply(this, n)
}
开始和结束可以是负的。 在这种情况下, 它们会从数组的末尾计数 。
如果只指定开始,则只删除一个元素。
函数返回新数组长度。
z = [0,1,2,3,4,5,6,7,8,9];
newlength = z.remove(2,6);
(8) [0, 1, 7, 8, 9]
z=[0,1,2,3,4,5,6,7,8,9];
newlength = z.remove(-4,-2);
(7) [0, 1, 2, 3, 4, 5, 9]
z=[0,1,2,3,4,5,6,7,8,9];
newlength = z.remove(3,-2);
(4) [0, 1, 2, 9]
我想根据ECMAScript 6. 假设你的阵列如下:
let arr = [1,2,3,4];
如果您想要删除像 2 这样的特殊索引, 请写下以下代码 :
arr.splice(2, 1); //=> arr became [1,2,4]
但如果您想要删除一个特殊项目, 如 3 和您不知道它的索引, 做如下 :
arr = arr.filter(e => e !== 3); //=> arr became [1,2,4]
提示 : 请使用箭头函数进行过滤回击, 除非您会得到空数组 。
您可以使用 lodash _. pull( 调和数组)、 _. pullAt( 调和数组) 或 _. 。 (不变换数组)
var array1 = ['a', 'b', 'c', 'd']
_.pull(array1, 'c')
console.log(array1) // ['a', 'b', 'd']
var array2 = ['e', 'f', 'g', 'h']
_.pullAt(array2, 0)
console.log(array2) // ['f', 'g', 'h']
var array3 = ['i', 'j', 'k', 'l']
var newArray = _.without(array3, 'i') // ['j', 'k', 'l']
console.log(array3) // ['i', 'j', 'k', 'l']
大部分答案都用...
循环的索引和组合删除过滤器
虽然所有解决方案都应该采用这些方法,但我想我们可以使用弦操纵。
需要注意的关于这一解决办法的要点 -- --
这将在数据中留下漏洞( 可以通过额外的过滤器将其移除 ) 此解决方案不仅适用于原始搜索值, 也适用于对象 。
诀窍是...
字符串字符串返回分隔符上的分解数据,以空字符串替换输入数据集中的搜索值。
remove = (input, value) => {
const stringVal = JSON.stringify(value);
const result = JSON.stringify(input)
return result.replace(stringVal, "").split(",");
}
本文创建了一个测试对象和数字的 JSF 中心- https://jsfidle.net/4t7zhkce/33/
检查小提琴中的移除方法 。
const newArray = oldArray.filter(item => item !== removeItem);