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

array.remove(value);

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


当前回答

我也碰到了这样的情况:我不得不从阵列中移除一个元素。 indexof没有在互联网探索器中工作, 因此我分享我的工作 jQuery.inArray () 解决方案 :

var index = jQuery.inArray(val, arr);
if (index > -1) {
    arr.splice(index, 1);
    //console.log(arr);
}

其他回答

var index,
    input = [1,2,3],
    indexToRemove = 1;
    integers = [];

for (index in input) {
    if (input.hasOwnProperty(index)) {
        if (index !== indexToRemove) {
            integers.push(result); 
        }
    }
}
input = integers;

此解决方案将需要一系列输入, 并将通过输入查找要删除的值。 这将在整个输入数组中循环, 结果将是第二个已经删除了特定索引的数组整数组。 然后将整数组复制到输入数组中 。

我设定了一个函数:

function pop(valuetoremove, myarray) {
    var indexofmyvalue = myarray.indexOf(valuetoremove);
    myarray.splice(indexofmyvalue, 1);
}

并用它这样:

pop(valuetoremove, myarray);

您可以使用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"]

2017-005-08

大多数给定的回答都用于严格的比较, 意思是两个对象在内存( 或原始类型) 中引用完全相同的对象, 但通常您想要从具有一定值的数组中删除一个非原始对象。 例如, 如果您给服务器打电话, 并想要对照本地对象检查已检索到的对象 。

const a = {'field': 2} // Non-primitive object
const b = {'field': 2} // Non-primitive object with same value
const c = a            // Non-primitive object that reference the same object as "a"

assert(a !== b) // Don't reference the same item, but have same value
assert(a === c) // Do reference the same item, and have same value (naturally)

//Note: there are many alternative implementations for valuesAreEqual
function valuesAreEqual (x, y) {
   return  JSON.stringify(x) === JSON.stringify(y)
}


//filter will delete false values
//Thus, we want to return "false" if the item
// we want to delete is equal to the item in the array
function removeFromArray(arr, toDelete){
    return arr.filter(target => {return !valuesAreEqual(toDelete, target)})
}

const exampleArray = [a, b, b, c, a, {'field': 2}, {'field': 90}];
const resultArray = removeFromArray(exampleArray, a);

//resultArray = [{'field':90}]

数值AreEqual有替代/更快的操作,但这样可以操作。如果您有特定的字段要检查,也可以使用自定义的比较器(例如,有些已检索的 UUID 相对于本地的 UUID ) 。

2. 还注意到这是一个功能操作,意即它不改变原始阵列。

一个非常天真的执行情况如下:

Array. prototype. remove = 函数( data) { const dataIdx = this. indexof( data) if (dataIdx { { { 0) { this.spice( dataIdx, 1) { 返回此. 长度;} } 允许 a = [1, 2,3] ; / / 这将将 Arr a 改为 [1, 3] a. remove(2) ;

我从函数返回数组的长度以遵守其他方法, 如 Array. prototype. push () 。