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

为何Lodash的_.has()对_.range()生成数组的最后一个元素返回false?

为什么_.has(r, 10)返回false?

我遇到一个bug,修复方法很简单(改用r.includes()),但不清楚原因。测试代码如下:

import _ from 'lodash';

console.log("TEST");
var r = _.range(1, 10 + 1);
console.log("_.range(1, 11):    " + r);
console.log("Array.isArray(r):  " + Array.isArray(r));
console.log("_.has(r, 2):       " + _.has(r, 2));
console.log("_.has(r, 20):      " + _.has(r, 20));
console.log("_.has(r, 10):      " + _.has(r, 10)); // ???
console.log("r.includes(10):    " + r.includes(10));

执行结果:

TEST 
_.range(1, 11):    1,2,3,4,5,6,7,8,9,10 
Array.isArray(r):  true 
_.has(r, 2):       true 
_.has(r, 20):      false 
_.has(r, 10):      false 
r.includes(10):    true 

为何_.has(r, 10)返回false?这是bug还是我理解有误?


原因解析

这不是bug,是对_.has的用途理解偏差了:

  • _.has的作用是判断对象(包括数组)是否拥有指定名称的自身可枚举属性。对于数组来说,索引就是它的属性名,但数组索引从0开始计数。
  • 你用_.range(1, 11)生成的数组是[1,2,3,4,5,6,7,8,9,10],数组长度length为10,有效索引范围是0到9——索引9对应的元素就是10。调用_.has(r, 10)时,实际是检查数组是否有名为"10"的属性(即索引10),显然不存在,所以返回false。
  • 而r.includes(10)是直接检查数组元素值是否存在,和属性/索引无关,因此能正确识别到值为10的元素,返回true。

如果要在Lodash里检查数组元素是否存在,应该用_.includes(r, 10),和原生includes作用一致,不要误用_.has。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 05:36:08