JavaScript中filter常见用法

filter 是 JavaScript 中的数组方法之一,用于筛选出符合条件的数组元素,返回一个新的数组。下面是 filter 的各种用法举例:

  1. 筛选出大于 5 的元素:
<code>const numbers = [1, 3, 5, 7, 9];
const filtered = numbers.filter((number) => number > 5);
// filtered = [7, 9]
</code>
  1. 筛选出偶数:
<code>const numbers = [1, 2, 3, 4, 5];
const filtered = numbers.filter((number) => number % 2 === 0);
// filtered = [2, 4]
</code>
  1. 筛选出包含某个字符串的元素:
<code>const fruits = ["apple", "banana", "cherry", "date"];
const filtered = fruits.filter((fruit) => fruit.includes("a"));
// filtered = ["apple", "banana"]
</code>
  1. 筛选出非空字符串:
<code>const strings = ["hello", "", "world", "   ", "goodbye"];
const filtered = strings.filter((string) => string.trim().length > 0);
// filtered = ["hello", "world", "goodbye"]
</code>
  1. 筛选出对象数组中某个属性值符合条件的元素:
<code>const users = [
  { name: "Alice", age: 20 },
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 40 },
];
const filtered = users.filter((user) => user.age > 25);
// filtered = [{ name: "Bob", age: 30 }, { name: "Charlie", age: 40 }]
</code>
  1. 筛选出数组中的唯一元素:
<code>const numbers = [1, 2, 3, 2, 4, 3, 5];
const unique = numbers.filter((number, index, array) => array.indexOf(number) === index);
// unique = [1, 2, 3, 4, 5]
</code>

这里的回调函数还接受了两个额外的参数 indexarray,分别表示当前元素的索引和原始数组,这样可以使用 indexOf 方法来判断当前元素是否已经在数组中出现过,从而筛选出唯一的元素。

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注