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

array.remove(value);

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


当前回答

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)

其他回答

如果您在数组中有复杂的对象, 您可以使用过滤器 。 在 $. in Array 或 tray. splice 不容易使用的情况下 。 特别是如果对象在数组中可能是浅的 。

例如,如果您有一个带有 Id 字段的对象,而您想要从数组中删除该对象:

this.array = this.array.filter(function(element, i) {
    return element.id !== idToRemove;
});
function array_remove(arr, index) {
    for (let i = index; i < arr.length - 1; i++) {
        arr[i] = arr[i + 1];
    }
    arr.length -= 1;
    return arr;
}
my_arr = ['A', 'B', 'C', 'D'];
console.log(array_remove(my_arr, 0));

这取决于你是否想保持一个空位。

如果你(如果)do do do 做想要一个空位 :

array[index] = undefined;

如果你(如果)不要想要一个空位 :

//To keep the original:
//oldArray = [...array];

//This modifies the array.
array.splice(index, 1);

如果您需要该项的值, 您可以保存返回的数组元素 :

var value = array.splice(index, 1)[0];

如果您要在数组两端的两端删除,可以使用array.pop()最后一个或最后一个array.shift()对第一个项目(两者都返回项目的价值) 。

如果你不知道项目的索引,你可以使用array.indexOf(item)以获得(在if()获得一个或一个while()以获得全部)))。array.indexOf(item)返回索引或-1尚未找到 。

我刚刚创建了一个多填充Array.prototype通过Object.defineProperty以删除数组中一个想要的元素,而不会在稍后通过for .. in ..

if (!Array.prototype.remove) {
  // Object.definedProperty is used here to avoid problems when iterating with "for .. in .." in Arrays
  // https://stackoverflow.com/questions/948358/adding-custom-functions-into-array-prototype
  Object.defineProperty(Array.prototype, 'remove', {
    value: function () {
      if (this == null) {
        throw new TypeError('Array.prototype.remove called on null or undefined')
      }

      for (var i = 0; i < arguments.length; i++) {
        if (typeof arguments[i] === 'object') {
          if (Object.keys(arguments[i]).length > 1) {
            throw new Error('This method does not support more than one key:value pair per object on the arguments')
          }
          var keyToCompare = Object.keys(arguments[i])[0]

          for (var j = 0; j < this.length; j++) {
            if (this[j][keyToCompare] === arguments[i][keyToCompare]) {
              this.splice(j, 1)
              break
            }
          }
        } else {
          var index = this.indexOf(arguments[i])
          if (index !== -1) {
            this.splice(index, 1)
          }
        }
      }
      return this
    }
  })
} else {
  var errorMessage = 'DANGER ALERT! Array.prototype.remove has already been defined on this browser. '
  errorMessage += 'This may lead to unwanted results when remove() is executed.'
  console.log(errorMessage)
}

删除整数值

var a = [1, 2, 3]
a.remove(2)
a // Output => [1, 3]

删除字符串值

var a = ['a', 'ab', 'abc']
a.remove('abc')
a // Output => ['a', 'ab']

删除布尔值

var a = [true, false, true]
a.remove(false)
a // Output => [true, true]

也可以通过此方法从数组中移除对象Array.prototype.remove方法。只需指定key => value of the Object您想要删除。

删除对象值

var a = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 3, b: 2}]
a.remove({a: 1})
a // Output => [{a: 2, b: 2}, {a: 3, b: 2}]

更新 :只有当您无法使用 ECMASCript 2015 (前称ES6) 时,才会推荐使用这种方法。 如果您可以使用这种方法, 其它答案则提供更清晰的落实。


这个格子在这里将解决您的问题, 并删除所有出现参数的情况, 而不是仅一个( 或指定值) 。

Array.prototype.destroy = function(obj){
    // Return null if no objects were found and removed
    var destroyed = null;

    for(var i = 0; i < this.length; i++){

        // Use while-loop to find adjacent equal objects
        while(this[i] === obj){

            // Remove this[i] and store it within destroyed
            destroyed = this.splice(i, 1)[0];
        }
    }

    return destroyed;
}

用法 :

var x = [1, 2, 3, 3, true, false, undefined, false];

x.destroy(3);         // => 3
x.destroy(false);     // => false
x;                    // => [1, 2, true, undefined]

x.destroy(true);      // => true
x.destroy(undefined); // => undefined
x;                    // => [1, 2]

x.destroy(3);         // => null
x;                    // => [1, 2]