admin管理员组文章数量:1424887
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
?
-
1
As you surmise, your best option in vanilla ES5 is
.indexOf()
as inarray.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
1 Answer
Reset to default 7ES2016: 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
本文标签: arraysVanilla Javascript equivalent for lodash includesStack Overflow
版权声明:本文标题:arrays - Vanilla Javascript equivalent for lodash _.includes - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745361859a2655333.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论