You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript的includes方法替代多条件或(||)逻辑判断

用数组includes替代多个||进行条件检查的正确实现

嘿,我来帮你理清楚这个问题~你现在的代码之所以达不到预期效果,是因为**Array.includes()是用来检查数组中是否存在某个完全匹配的元素**,而你的cars数组里的元素都是对象,你传入的['BMW', 'Audi']是一个数组,显然和数组里的对象不匹配,所以会返回false。

下面根据你的实际需求给出两种正确的实现方式:

1. 判断数组中是否存在符合条件的元素(替代多个||的存在性检查)

如果你只是想确认cars里有没有品牌是BMW或Audi的车,可以用Array.some()结合includes:

const cars = [{ name: 'BMW', year: '2020' }, { name: 'Audi', year: '2019' }, { name: 'Benz', year: '2018' }];
const targetBrands = ['BMW', 'Audi'];
// some方法只要有一个元素满足条件就返回true
const hasTargetCar = cars.some(car => targetBrands.includes(car.name));
console.log(hasTargetCar); // 输出 true

这样就替代了原本需要写car.name === 'BMW' || car.name === 'Audi'的逻辑,后续要添加新品牌,直接往targetBrands数组里加就行,非常灵活。

2. 筛选出所有符合条件的元素

如果你想把所有品牌是BMW或Audi的车都筛选出来,就用Array.filter():

const cars = [{ name: 'BMW', year: '2020' }, { name: 'Audi', year: '2019' }, { name: 'Benz', year: '2018' }];
const targetBrands = ['BMW', 'Audi'];
// filter方法返回所有满足条件的元素组成的新数组
const result = cars.filter(car => targetBrands.includes(car.name));
console.log(result); 
// 输出 [{ name: 'BMW', year: '2020' }, { name: 'Audi', year: '2019' }]

简单总结一下:

  • 不要直接给cars.includes()传目标品牌数组,因为数组元素类型不匹配
  • 先把要匹配的目标值放到一个数组里(比如targetBrands)
  • 用some或filter遍历cars,在回调里用targetBrands.includes(car.name)来做条件判断

内容的提问来源于stack exchange,提问作者scriobh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 09:22:28