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

如何使用Array.find()实现类似MySQL的DateTime范围查询筛选数组对象

问题修正方案

核心问题说明

  • 原有第(6)段代码的逻辑错误:用&&判断时间同时等于两个不同值,不可能成立,范围查询应该用大于/小于判断
  • 你使用的YYYY-MM-DD HH:mm:ss格式的时间字符串,字典排序和时间顺序完全一致,可以直接比较大小,也可以转成Date时间戳比较,兼容性更强
  • 注意:Array.find() 仅返回第一个匹配的记录,如果需要返回所有符合条件的结果,对应MySQL返回多条的SELECT语句,应该使用Array.filter()

修正后的代码

第(6)部分实现(仅返回第一条匹配记录)

// (6) - Select * FROM tblUsers WHERE created BETWEEN '2021-01-05 00:00:01' AND '2021-01-10 00:00:01';
// 方案1:直接比较字符串(适配当前固定日期格式)
let userRecordsByDateTimeRange: any = tblUsers.find(record => 
  record.created >= '2021-01-05 00:00:01' && record.created <= '2021-01-10 00:00:01'
) || null;
console.log(userRecordsByDateTimeRange);

// 方案2:转时间戳比较(兼容非标准日期格式场景)
let userRecordsByDateTimeRange2: any = tblUsers.find(record => {
  const createTimestamp = new Date(record.created).getTime();
  const startTimestamp = new Date('2021-01-05 00:00:01').getTime();
  const endTimestamp = new Date('2021-01-10 00:00:01').getTime();
  return createTimestamp >= startTimestamp && createTimestamp <= endTimestamp
}) || null;
console.log(userRecordsByDateTimeRange2);

第(6)部分实现(返回所有匹配记录)

// 返回所有符合时间范围的记录,对应MySQL返回多条结果的查询
let allUserRecordsByDateTimeRange: any = tblUsers.filter(record => 
  record.created >= '2021-01-05 00:00:01' && record.created <= '2021-01-10 00:00:01'
) || [];
console.log(allUserRecordsByDateTimeRange);

原有代码其他小错误修正

第(4)段查询逻辑的判断条件写错,你要匹配lastName为Murray的记录,原有代码写的是和Bill比较,修正后:

// (4) - Select * FROM tblUsers WHERE lastName = 'Murray';
let selectUserByLastName: any = tblUsers.find(record => record.lastName === 'Murray') || null;
console.log(selectUserByLastName);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:36:03