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

为什么对象数组调用.includes()方法无法匹配到已存在的元素?

问题原因

  • JavaScript 中 Array.includes() 对引用类型做比对时,比较的是变量的内存引用地址而非对象的属性值。你代码中定义的 date 对象和 schedule 数组里的日期对象虽然 delivery_date 属性值完全一致,但属于两个独立创建的对象,指向不同的内存地址,所以 includes() 会判定为不存在。

修复方案

把 order.product.schedule.includes(date) 替换为用 Array.some() 比对对象属性值即可,你可以直接提取目标日期字符串做比对,修改后的代码如下:

// 也可以保留原有date对象,比对时取date.delivery_date即可
const targetDate = '2021-10-07';

const customers = 
  [ { first_name: 'Doris'
    , orders: 
      [ { product:
          { name: 'White shell', price: 10, schedule: 
            [ { delivery_date: '2021-10-07' } 
            , { delivery_date: '2021-10-14' } 
        ] } } 
      , { product: 
          { name: 'Pink shell', price: 15, schedule: 
            [ { delivery_date: '2021-10-07' } 
    ] } } ] } 
  , { first_name: 'Nemo'
    , orders: 
      [ { product: 
          { name: 'Carbonated water', price: 10, schedule: 
            [ { delivery_date: '2021-10-07' } 
            , { delivery_date: '2021-10-14' } 
  ] } } ] } ];

const res = customers.filter(function(customer) {
  return customer.orders.some(function(order) {
    // 逐行比对schedule项的delivery_date属性值
    return order.product.schedule.some(item => item.delivery_date === targetDate);
  });
});

console.log(res);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 04:18:04