admin管理员组文章数量:1426058
For a JavaScript array, the includes(value)
function returns true, if and only if the array contains the value.
What is a good and performant equivalent to check, whether a value is included in an iterator (e.g. map.values()
)?
First approach (maybe not the most performant one):
Array.from(it).includes(value)
Second approach (not that short):
const iteratorIncludes = (it, value) => {
for (x of it) {
if (x === value) return true
}
return false
}
iteratorIncludes(it, value)
For a JavaScript array, the includes(value)
function returns true, if and only if the array contains the value.
What is a good and performant equivalent to check, whether a value is included in an iterator (e.g. map.values()
)?
First approach (maybe not the most performant one):
Array.from(it).includes(value)
Second approach (not that short):
const iteratorIncludes = (it, value) => {
for (x of it) {
if (x === value) return true
}
return false
}
iteratorIncludes(it, value)
Share
Improve this question
asked Sep 27, 2020 at 21:17
YannicYannic
82810 silver badges27 bronze badges
5
-
1
map.has()
Map.prototype.has() – pilchard Commented Sep 27, 2020 at 21:26 - 2 @pilchard, this checks only the key of a map. – Nina Scholz Commented Sep 27, 2020 at 21:27
-
That second one looks good. Sure, you need to stow away the helper function somewhere, but the call is short and efficient. Alternatively, use the proposed iterator helpers and check
it.some(v => v === value)
. – Bergi Commented Sep 27, 2020 at 21:28 - @Bergi can you make an answer? – qwr Commented Jun 15, 2021 at 22:40
- @qwr done, see below – Bergi Commented Jun 16, 2021 at 9:28
1 Answer
Reset to default 5Your second approach looks good. Sure, you need to stow away the helper function somewhere, but you need to declare it only once so it doesn't matter - the call is short and efficient (even shorter than your first approach).
Alternatively, use the proposed iterator helpers and check it.some(v => v === value)
1. They don't offer an includes
method that mirrors the Array
API yet.
1: Technically, includes
uses the SameValueZero parison, which has a different result than ===
for a value
of NaN
.
本文标签: arraysJavaScript check whether iterator includes valueStack Overflow
版权声明:本文标题:arrays - JavaScript check whether iterator includes value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745466686a2659561.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论