簡體   English   中英

如何從javascript中的數組中刪除某些匹配條件的元素?

[英]How do I remove certain elements matching criteria from an array in javascript?

我有一個數組。

const arr = ['apple', 'banana', 'pear', 'orange', 'peach'];

測試功能是這樣的。

function test(str) {
  return str.length >= 6;
}

我可以使用filter方法輕松找到元素。 但我想從數組中刪除這些元素。

結果應該是

['apple', 'pear', 'peach']

Javascript 有一個函數, Array.prototype.filter

const arr = ['apple', 'banana', 'pear', 'orange', 'peach'];
function test(str) {
    return str.length >= 6;
}

// we need to negate the result since we want to keep elements where test returns false
console.log(arr.filter(x => !test(x)));
// logs: ['apple', 'pear', 'peach']

除了給定的Array#filter方法

array.filter(string => !test(string))

您可以利用函數方法的優勢,該方法采用函數並重新調整它的否定結果。

 function test(str) { return str.length >= 6; } function not(fn) { return (...args) => !fn(...args); } const array = ['apple', 'banana', 'pear', 'orange', 'peach'], result = array.filter(not(test)); console.log(result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM