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

array.remove(value);

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


当前回答

您可以使用

Array.splice(index);

其他回答

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

您可以使用标准__proto__JavaScript 和定义此函数。例如,

let data = [];
data.__proto__.remove = (n) => { data = data.flatMap((v) => { return v !== n ? v : []; }) };

data = [1, 2, 3];
data.remove(2);
console.log(data); // [1,3]

data = ['a','b','c'];
data.remove('b');
console.log(data); // [a,c]

使用欧 6扩展操作员 。

比方说你想删除4。

let array = [1,2,3,4,5]
const index = array.indexOf(4)
let new_array = [...array.slice(0,index), ...array.slice(index+1, array.length)]
console.log(new_array)
=> [1, 2, 3, 5]

从字符串阵列中查找和删除一个特定的字符串:

var colors = ["red","blue","car","green"];
var carIndex = colors.indexOf("car"); // Get "car" index
// Remove car from the colors array
colors.splice(carIndex, 1); // colors = ["red", "blue", "green"]

资料来源:https://www.codegrepper.com/?search_term=remove+a+particular+element+from+array

 (function removeFromArrayPolyfill() {
      if (window.Array.prototype.remove) return;
    
      Array.prototype.remove = function (value) {
        if (!this.length || !value) return;
    
        const indexOfValue = this.indexOf(value);
    
        if (indexOfValue >= 0) {
          this.splice(indexOfValue, 1);
        }
      };
    })();
    
    // testing polyfill
    const nums = [10, 20, 30];
    nums.remove(20);
    console.log(nums);//[10,30]