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

array.remove(value);

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


当前回答

我刚刚创建了一个多填充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}]

其他回答

您可以使用

Array.splice(index);

有许多方法可以删除指定元素从 JavaScript 阵列中得出的。 以下是我研究中可以想到的五种最佳方法。

1. 直接使用“ splice () ” 方法

在以下代码段,从数组中删除特定预定位置的元素。

  • 语法 :数组_ name. spice( begin_ index, 数字_ elements_ remove ) ; 数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组, remove;
  • 应用程序 :

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

console.log("Original array: " + arr);

var removed = arr.splice(4, 2);

console.log("Modified array: " + arr);

console.log("Elements removed: " + removed);

2. 使用“ splice() () ” 方法用“ valice () ” 方法用“ value () ” 删除元素

在以下代码段的以下代码段中,如果条件在用于循环。

var arr = [1, 2, 6, 3, 2, 6, 7, 8, 9, 10];

console.log("Original array: " + arr);

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

  if (arr[i] === 6) {

    var removed = arr.splice(i, 1);
    i--;
  }

}

console.log("Modified array: " + arr); // 6 is removed
console.log("Removed elements: " + removed);

3. 使用“过滤器()”方法删除按值选择的元素

与使用“ spice() () ” 方法的执行类似, 但它没有改变现有的数组, 而是创造了新的元素阵列, 从而删除了不想要的元素 。

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var filtered = array.filter(function(value, index, arr) {
  return value != 6 ;
});

console.log("Original array: "+array);

console.log("New array created: "+filtered); // 6 is removed

4. 在“ Lodash” JavaScript 库中使用“ remove () ” 方法

在下面的代码段中, JavaScript 库里有叫作“ Lodash ” 的删除() 方法。 这个方法也与过滤方法相似 。

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log("Original array: " + array);

var removeElement = _.remove(array, function(n) {
  return n === 6;
});

console.log("Modified array: " + array);
console.log("Removed elements: " + removeElement); // 6 is removed
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

5. 制作自定义除去方法

JavaScript没有本地的“ array. remove” 方法, 但我们可以创建一种使用以上方法的方法, 用于在以下代码片段中执行 。

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

function arrayRemove(arr, value) {

  return arr.filter(function(element) {
    return element != value;
  });
}

console.log("Original array: " + array);
console.log("Modified array: " + arrayRemove(array, 6)); // 6 is removed

最后方法(第5项)更适合解决上述问题。

您可以从数组中添加一个原型函数来“ 移除” 元素 。

以下示例显示当我们知道一个元素的索引时如何简单地从数组中删除一个元素。Array.filter方法。

Array.prototype.removeByIndex = function(i) {
    if(!Number.isInteger(i) || i < 0) {
        // i must be an integer
        return this;
    }

    return this.filter((f, indx) => indx !== i)
}
var a = [5, -89, (2 * 2), "some string", null, false, undefined, 20, null, 5];

var b = a.removeByIndex(2);
console.log(a);
console.log(b);

有时候我们不知道元素的索引

Array.prototype.remove = function(i) {
    return this.filter(f => f !== i)
}
var a = [5, -89, (2 * 2), "some string", null, false, undefined, 20, null, 5];

var b = a.remove(5).remove(null);
console.log(a);
console.log(b);

// It removes all occurrences of searched value

但是,当我们只想要删除搜索值的首次出现时,我们就可以使用Array.indexOf函数中的方法。

Array.prototype.removeFirst = function(i) {
    i = this.indexOf(i);

    if(!Number.isInteger(i) || i < 0) {
        return this;
    }

    return this.filter((f, indx) => indx !== i)
}
var a = [5, -89, (2 * 2), "some string", null, false, undefined, 20, null, 5];

var b = a.removeFirst(5).removeFirst(null);
console.log(a);
console.log(b);

减少方法的利润如下:

(a) 需要按索引删除某一要素:

function remove(arr, index) {
  return arr.reduce((prev, x, i) => prev.concat(i !== index ? [x] : []), []);
}

b) 需要删除元素值(int)的元素:

function remove(arr, value) {
  return arr.reduce((prev, x, i) => prev.concat(x !== value ? [x] : []), []);
}

这样我们就可以返回一个新的阵列( 将会以酷酷的功能方式- 比使用推或组合要好得多) , 并删除元素 。

spolice () 函数能够将数组中的项目还给您, 从特定的索引中删除项目 / 项 :

function removeArrayItem(index, array) {
    array.splice(index, 1);
    return array;
}

let array = [1,2,3,4];
let index = 2;
array = removeArrayItem(index, array);
console.log(array);