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

array.remove(value);

我必须使用核心核心核心JavaScript。 不允许框架 。


当前回答

Array.prototype.remove = function(x) {
    var y=this.slice(x+1);
    var z=[];
    for(i=0;i<=x-1;i++) {
        z[z.length] = this[i];
    }

    for(i=0;i<y.length;i++){
        z[z.length]=y[i];
    }

    return z;
}

其他回答

如果您使用现代浏览器, 您可以使用. 过滤器 。

Array.prototype.remove = function(x){
    return this.filter(function(v){
        return v !== x;
    });
};

var a = ["a","b","c"];
var b = a.remove('a');

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

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']

我喜欢这个单行道:

arr.includes(val) && arr.splice(arr.indexOf(val), 1)
  • 欧 6(无 (没有) (没有) (没有) (没有)Internet 探索器支助))
  • 在原地清除。
  • 快速: 不重复重复重复或重复 。
  • 支持删除这些值nullundefined

作为原型

// remove by value. return true if value found and removed, false otherwise
Array.prototype.remove = function(val)
{
    return this.includes(val) && !!this.splice(this.indexOf(val), 1);
}

(是的,我读了所有其他的答案 却找不到一个结合的答案)includessplice在同一行中。 )

您可以扩展数组对象以定义自定义的删除函数如下:

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