繁体   English   中英

在JS中按值从数组中删除多个元素

[英]Remove multiple elements from array by value in JS

当我想删除一个元素时,这很容易。 这是我的功能:

function removeValues(array, value) {
    for(var i=0; i<array.length; i++) {
        if(array[i] == value) {
            array.splice(i, 1);
            break;
        }
    }
    return array;
}

但是如何删除多个元素?

这是一个使用 ES7 的简单版本:

// removing values
let items = [1, 2, 3, 4];
let valuesToRemove = [1, 3, 4]
items = items.filter((i) => !valuesToRemove.includes(i))

对于 ES6 的简单版本

// removing values
let items =[1, 2, 3, 4];
let valuesToRemove = [1, 3, 4]
items = items.filter((i) => (valuesToRemove.indexOf(i) === -1))
const items = [0, 1, 2, 3, 4]; [1, 4, 3].reverse().forEach((index) => { items.splice(index, 1) }) // [0, 2, 4]

我相信你会在 Javascript 的内置数组函数中找到你正在寻找的那种功能......特别是Array.map(); Array.filter();

 //Array Filter function isBigEnough(value) { return value >= 10; } var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); // filtered is [12, 130, 44] //Array Map (Can also be used to filter) var numbers = [1, 4, 9]; var doubles = numbers.map(function(num) { return num * 2; }); // doubles is now [2, 8, 18]. numbers is still [1, 4, 9] /////UPDATE REFLECTING REMOVAL OF VALUES USING ARRAY MAP var a = [1,2,3,4,5,6]; a.map(function(v,i){ if(v%2==0){ a.pop(i); } }); console.log(a); // as shown above all array functions can be used within the call back to filter the original array. Alternativelty another array could be populated within the function and then aassigned to the variable a effectivley reducing the array.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM