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

array.remove(value);

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


当前回答

理解这一点:

您可以使用 JavaScript 阵列来组合数值, 并在它们上面循环。 数组项目可以以多种方式被添加和删除。 总共有9种方法( 使用其中适合你的任何一种方法) 。 JavaScript 阵列不使用删除方法, 而是有多种方法可以清除数组值 。

这样做的不同方法:

您可以以这些方式从 JavaScript 阵列中删除元素 :

1- 流行 :从矩阵结尾处删除 。

2-轮班:从数组的开头删除。

3 - Splice: 3 - splice: 3 - splice: 3 - splice: 3 - splice:从特定的矩阵索引中删除。

4- 过滤器 :这将允许您从阵列中从程序上删除元素 。


方法1:从 JavaScript 队列起始时删除元素

var ar = ['zero', 'one', 'two', 'three'];
    
ar.shift(); // returns "zero"
    
console.log( ar ); // ["one", "two", "three"]

方法2:从 JavaScript 阵列结尾删除元素

var ar = [1, 2, 3, 4, 5, 6];
    
ar.length = 4; // set length to remove elements
console.log( ar ); // [1, 2, 3, 4]


var ar = [1, 2, 3, 4, 5, 6];
    
ar.pop(); // returns 6
    
console.log( ar ); // [1, 2, 3, 4, 5]

方法3:在 JavaScript 中使用重复来移除队列元素

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

var removed = arr.splice(2,2);
console.log(arr);


var list = ["bar", "baz", "foo", "qux"];
    
list.splice(0, 2); 
console.log(list);

方法4:使用 Splice 依据值删除队列项目

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    
    for( var i = 0; i < arr.length; i++){ 
    
        if ( arr[i] === 5) { 
    
            arr.splice(i, 1); 
        }
    
    }
    
    //=> [1, 2, 3, 4, 6, 7, 8, 9, 10]
    
    
var arr = [1, 2, 3, 4, 5, 5, 6, 7, 8, 5, 9, 10];
    
    for( var i = 0; i < arr.length; i++){ 
                                   
        if ( arr[i] === 5) { 
            arr.splice(i, 1); 
            i--; 
        }
    }

    //=> [1, 2, 3, 4, 6, 7, 8, 9, 10]

方法5:使用队列过滤器方法按值删除项目

  var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    var filtered = array.filter(function(value, index, arr){ 
        return value > 5;
    });
    //filtered => [6, 7, 8, 9]
    //array => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

方法6:Lodash 队列删除方法

var array = [1, 2, 3, 4];
var evens = _.remove(array, function(n) { 
                  return n % 2 === 0;
            });
            
console.log(array);// => [1, 3]console.log(evens);// => [2, 4]

方法7:制作删除方法

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

function arrayRemove(arr, value) { 
    
        return arr.filter(function(ele){ 
            return ele != value; 
        });
    }
    
var result = arrayRemove(array, 6); // result = [1, 2, 3, 4, 5, 7, 8, 9, 10]

方法8:使用删除运算符明确删除队列元素

var ar = [1, 2, 3, 4, 5, 6];
    
delete ar[4]; // delete element with index 4
    
console.log( ar ); // [1, 2, 3, 4, undefined, 6]
    
alert( ar ); // 1,2,3,4,,6

方法9:清除或重置 JavaScript 阵列

var ar = [1, 2, 3, 4, 5, 6];
//do stuffar = [];
//a new, empty array!

var arr1 = [1, 2, 3, 4, 5, 6];
var arr2 = arr1; 
    // Reference arr1 by another variable arr1 = [];
    
console.log(arr2); 
// Output [1, 2, 3, 4, 5, 6]

var arr1 = [1, 2, 3, 4, 5, 6];
var arr2 = arr1; 
    // Reference arr1 by another variable arr1 = [];
    
console.log(arr2); 
// Output [1, 2, 3, 4, 5, 6]

摘要:

关键是要通过删除 JavaScript 矩阵项目来管理您的数据。 虽然没有单一的“ 撤销” 功能, 但您可以使用各种方式和战略清除不必要的阵列元素 。

其他回答

查找index使用indexOf,然后删除该索引splice.

组合法通过删除现有元素和/或添加新元素来改变数组的内容。

const array = [2, 5, 9];

console.log(array);

const index = array.indexOf(5);
if (index > -1) { // only splice array when item is found
  array.splice(index, 1); // 2nd parameter means remove one item only
}

// array = [2, 9]
console.log(array); 

第二个参数的第二个参数splice是要删除的元素数。请注意splice修改现有数组,并返回含有已删除元素的新数组。


由于完整性的原因,此处为函数。第一个函数只删除一个单一事件(即删除第一个匹配5调自[2,5,9,1,5,8,5]),而第二个函数删除所有事件:

function removeItemOnce(arr, value) {
  var index = arr.indexOf(value);
  if (index > -1) {
    arr.splice(index, 1);
  }
  return arr;
}

function removeItemAll(arr, value) {
  var i = 0;
  while (i < arr.length) {
    if (arr[i] === value) {
      arr.splice(i, 1);
    } else {
      ++i;
    }
  }
  return arr;
}
// Usage
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
console.log(removeItemAll([2,5,9,1,5,8,5], 5))

在类型Script中,这些函数可用类型参数保持类型安全:

function removeItem<T>(arr: Array<T>, value: T): Array<T> { 
  const index = arr.indexOf(value);
  if (index > -1) {
    arr.splice(index, 1);
  }
  return arr;
}

正在删除带有索引和相交点的值 !

function removeArrValue(arr,value) {
    var index = arr.indexOf(value);
    if (index > -1) {
        arr.splice(index, 1);
    }
    return arr;
}

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

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

this.array = this.array.filter(function(element, i) {
    return element.id !== idToRemove;
});

我还有一个从阵列中移除的好办法:

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

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