js实现多项查询
实现多项查询的方法
在JavaScript中实现多项查询通常涉及数组操作、对象筛选或API请求。以下是几种常见场景的实现方式:
数组筛选查询
使用filter()方法从数组中筛选满足多个条件的项:

const products = [
{ id: 1, name: 'Laptop', price: 999, inStock: true },
{ id: 2, name: 'Phone', price: 699, inStock: false },
{ id: 3, name: 'Tablet', price: 499, inStock: true }
];
const filtered = products.filter(item =>
item.price < 700 &&
item.inStock === true
);
对象属性查询
检查对象是否满足多个条件:
const user = {
name: 'Alice',
age: 25,
isAdmin: false
};
const meetsCriteria = (
user.age >= 18 &&
user.isAdmin === false
);
API多条件查询
使用URL参数实现多条件查询:

async function fetchUsers(filters) {
const params = new URLSearchParams();
if (filters.name) params.append('name', filters.name);
if (filters.age) params.append('age', filters.age);
const response = await fetch(`/api/users?${params}`);
return response.json();
}
// 使用示例
fetchUsers({ name: 'Alice', age: 25 });
动态条件构建
对于不确定数量的查询条件,可以动态构建查询对象:
function buildQuery(criteria) {
const query = {};
if (criteria.minPrice) {
query.price = { $gte: criteria.minPrice };
}
if (criteria.category) {
query.category = criteria.category;
}
return query;
}
正则表达式多条件
使用正则表达式进行复杂文本查询:
const searchText = 'error 404';
const regex = new RegExp(
searchText
.split(' ')
.map(term => `(?=.*${term})`)
.join(''),
'i'
);
const results = logs.filter(log => regex.test(log.message));






