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
Add a ment  | 

1 Answer 1

Reset to default 5

Your 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