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

array.remove(value);

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


当前回答

您在数组中有 1 到 9 个, 您想要删除 5 个 。 请使用以下代码 :

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

var newNumberArray = numberArray.filter(m => {
  return m !== 5;
});

console.log("new Array, 5 removed", newNumberArray);


如果您想要多个值。例如:- 1,7,8

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

var newNumberArray = numberArray.filter(m => {
  return (m !== 1) && (m !== 7) && (m !== 8);
});

console.log("new Array, 1,7 and 8 removed", newNumberArray);


如果您想要删除数组中的数组值。 例如 : [3,4,5]

var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var removebleArray = [3,4,5];

var newNumberArray = numberArray.filter(m => {
    return !removebleArray.includes(m);
});

console.log("new Array, [3,4,5] removed", newNumberArray);

包括支持的浏览器链接链接.

其他回答

Array.prototype.removeByValue = function (val) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] === val) {
      this.splice(i, 1);
      i--;
    }
  }
  return this;
}

var fruits = ['apple', 'banana', 'carrot', 'orange'];
fruits.removeByValue('banana');

console.log(fruits);
// -> ['apple', 'carrot', 'orange']

非就地解决办法

arr.slice(0,i).concat(arr.slice(i+1));

let arr = [10, 20, 30, 40, 50]

let i = 2 ; // position to remove (starting from 0)
let r = arr.slice(0,i).concat(arr.slice(i+1));

console.log(r);

我张贴我的代码,删除一个阵列元素, 并缩短阵列长度 。

function removeElement(idx, arr) {
    // Check the index value
    if (idx < 0 || idx >= arr.length) {
        return;
    }
    // Shift the elements
    for (var i = idx; i > 0; --i) {
        arr[i] = arr[i - 1];
    }
    // Remove the first element in array
    arr.shift();
}

我喜欢这个单行道:

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在同一行中。 )

您可以使用Set,然后使用delete函数 :

const s = Set;
s.add('hello');
s.add('goodbye');
s.delete('hello');