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

array.remove(value);

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


当前回答

const arr = [1, 2, 3, 4, 5]
console.log(arr) // [ 1, 2, 3, 4, 5 ]

假设你想从Arr删除3号

const newArr = arr.filter(w => w !==3)
console.log(newArr) // [ 1, 2, 4, 5 ]

其他回答

大部分答案都用...

  1. 索引和交点
  2. 删除删除
  3. 过滤过滤器
  4. 常设经常经常 经常经常for loop

虽然所有解决办法都应采用这些方法,但我认为我们可以使用字符串操作.

需要注意的关于这一解决办法的要点 -- --

  1. 它会在数据中留下漏洞(可以通过额外的过滤器来清除)
  2. 此解决方案不仅用于原始搜索值,而且用于工作对象.

诀窍是...

  1. stringify数据集和搜索值
  2. 用空字符串替换输入数据集中的搜索值
  3. 返回返回split分隔符上的数据,.
    remove = (input, value) => {
        const stringVal = JSON.stringify(value);
        const result = JSON.stringify(input)

        return result.replace(stringVal, "").split(",");
    }

这里创建了一个测试对象和数字 JSF 的 JSF 。 。 。https://jsfiddle.net/4t7zhkce/33/

检查remove方法在小提琴中。

我对基底 JavaScript 阵列进行了相当高效的扩展:

Array.prototype.drop = function(k) {
  var valueIndex = this.indexOf(k);
  while(valueIndex > -1) {
    this.removeAt(valueIndex);
    valueIndex = this.indexOf(k);
  }
};
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;

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

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

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

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

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