在 JavaScript 中使用多个条件过滤数组
要使用多个条件过滤数组:
-
使用
Array.filter()
方法迭代数组。 -
使用逻辑 AND
&&
运算符检查多个条件。 -
Array.filter()
方法将返回所有满足条件的元素。
const people = [
{name: 'Adam', age: 30},
{name: 'Bob', age: 40},
{name: 'Carl', age: 30},
];
const results = people.filter(element => {
// 👇️ using AND (&&) operator
return element.age === 30 && element.name === 'Carl';
});
// 👉️ [ {name: 'Carl', age: 30} ]
console.log(results);
我们传递给 Array.filter()
方法的函数会被数组中的每个元素调用。
如果函数返回真值,则将相应的数组元素添加到结果数组中。
我们使用
&&
(和)运算符检查多个条件。
如果两个条件都满足,该元素将仅添加到过滤后的数组中。
示例中的函数检查当前对象是否具有值为 30 的年龄属性和值为 Carl 的名称属性。
如果回调函数从不返回真值,则 Array.filter()
返回一个空数组。
如果我们需要过滤具有多个条件的数组,而只需满足一个条件,请使用 Array.filter()
方法和逻辑或 ||
操作员。
const people = [
{name: 'Adam', age: 30},
{name: 'Bob', age: 40},
{name: 'Carl', age: 30},
];
const results = people.filter(element => {
// 👇️ using OR (||) operator
return element.age === 40 || element.name === 'Carl';
});
// 👉️ [{name: 'Bob', age: 40}, {name: 'Carl', age: 30}]
console.log(results);
我们使用了逻辑或 ||
运算符检查多个条件。
如果任一条件返回真值,则相应的元素将包含在结果数组中。
在代码示例中,我们检查属性年龄等于 40 的对象或属性名称等于 Carl 的对象。
数组中的 2 个元素至少满足 2 个条件中的一个,因此 Array.filter()
方法返回这两个条件。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。