如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
删除在索引i 上的元素, 不突变原始数组 :
/**
* removeElement
* @param {Array} array
* @param {Number} index
*/
function removeElement(array, index) {
return Array.from(array).splice(index, 1);
}
// Another way is
function removeElement(array, index) {
return array.slice(0).splice(index, 1);
}
其他回答
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)
}
start
和end
可以是负数。在这种情况下,它们会从数组的末尾计数。
如果只有start
中指定,只删除一个元素。
函数返回新数组长度。
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]
您可以使用ES6. 例如,在此情况下删除值“ 3” :
var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');
console.log(newArray);
产出:
["1", "2", "4", "5", "6"]
ES6且无突变:(2016年10月)
const removeByIndex = (list, index) =>
[
...list.slice(0, index),
...list.slice(index + 1)
];
output = removeByIndex([33,22,11,44],1) //=> [33,11,44]
console.log(output)
您可以扩展数组对象以定义自定义的删除函数如下:
let numbers = [1,2,4,4,5,3,45,9];
numbers.delete = function(value){
var indexOfTarget = this.indexOf(value)
if(indexOfTarget !== -1)
{
console.log("array before delete " + this)
this.splice(indexOfTarget, 1)
console.log("array after delete " + this)
}
else{
console.error("element " + value + " not found")
}
}
numbers.delete(888)
// Expected output:
// element 888 not found
numbers.delete(1)
// Expected output;
// array before delete 1,2,4,4,5,3,45,9
// array after delete 2,4,4,5,3,45,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]
提示提示:请使用箭头函数进行过滤回击,除非您得到空数组。