最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - Vanilla Javascript equivalent for lodash _.includes - Stack Overflow

programmeradmin1浏览0评论

I'm using the lodash includes function to check if a target value exists in an array...

_.includes(array, target) 

and was hoping to find a good equivalent in ES5 (or ES6)

Did I miss something? Is there no ES5 Array.prototype equivalent?

Or is my only option to use indexOf?

I'm using the lodash includes function to check if a target value exists in an array...

_.includes(array, target) 

and was hoping to find a good equivalent in ES5 (or ES6)

Did I miss something? Is there no ES5 Array.prototype equivalent?

Or is my only option to use indexOf?

Share Improve this question edited Oct 9, 2016 at 4:53 sfletche asked Jul 17, 2015 at 0:04 sfletchesfletche 49.9k31 gold badges109 silver badges120 bronze badges 4
  • 1 As you surmise, your best option in vanilla ES5 is .indexOf() as in array.indexOf(target) !== -1. – jfriend00 Commented Jul 17, 2015 at 0:06
  • There is also Array.prototype.some if you want something a bit smarter than indexOf (also see MDN), so array.some(function(o){return o === target}). – RobG Commented Jul 17, 2015 at 0:27
  • Just out of curiosity, what's wrong with lodash includes()? – Adam Boduch Commented Jul 17, 2015 at 18:37
  • 1 @AdamBoduch - No plaints about lodash. I love lodash. Just exploring the pain point for removing the dependency. – sfletche Commented Jul 17, 2015 at 18:52
Add a ment  | 

1 Answer 1

Reset to default 7

ES2016: Array.prototype.includes()

[1, 2, 3].includes(2);     // true

ES5: Array.prototype.indexOf() >= 0

[2, 5, 9].indexOf(5) >= 0;   // true
[2, 5, 9].indexOf(7) >= 0;   // false

If you prefer a function:

function includes (array, element) { return array.indexOf(element) >= 0 }

and use it as:

includes([2, 5, 9], 5);    // true
发布评论

评论列表(0)

  1. 暂无评论