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

lodash或原生JS中是否存在与includes功能相反的amongst等效函数?

Lodash 反向 includes 方法实现方案

你可以通过 Lodash 提供的自定义混合(mixin)能力快速实现需求,完全复用内置方法的兼容逻辑,不需要额外造轮子。


核心实现

直接注册自定义方法到 Lodash 实例中:

// 注册 amongst 方法
_.mixin({
  amongst: (targetValue, collection) => _.includes(collection, targetValue)
}, { chain: true })

注册完成后就可以按你期望的方式调用:

// 基础用法
_(42).amongst(['a', 42]) // 返回 true
_('test').amongst(['demo', 'test']) // 返回 true

// 兼容 NaN 匹配,和原生 includes 行为一致
_(NaN).amongst([1, NaN, 3]) // 返回 true

// 支持字符串作为目标集合
_('c').amongst('abcdef') // 返回 true

拓展配置

如果需要同时支持 within 作为别名,可以一次性注册两个方法:

_.mixin({
  amongst: (val, coll) => _.includes(coll, val),
  within: (val, coll) => _.includes(coll, val)
}, { chain: true })

上述实现完全复用 Lodash 内置 includes 的所有逻辑,自动处理类型判断、边界兼容、稀疏数组等场景,不需要额外做适配。


无依赖原生实现(不推荐全局污染,仅做参考)

如果不想依赖 Lodash,也可以直接通过原型扩展实现,仅推荐在封闭业务场景下使用:

Object.prototype.amongst = function (collection) {
  return collection.includes(this.valueOf())
}

// 调用示例
(42).amongst([1,42,3]) // true
('b').amongst('abc') // true

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 11:45:03