Home > Web Front-end > JS Tutorial > How does js determine that an array contains specific elements? (Method summary)

How does js determine that an array contains specific elements? (Method summary)

不言
Release: 2018-09-18 15:07:18
Original
2474 people have browsed it

The content of this article is about how js determines that an array contains specific elements? (Method summary) has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

It is a very common requirement to determine whether an array contains a specific element. There are many implementation methods in JavaScript. I have some time to summarize them today. They are sorted from strong to weak compatibility. The return type is always boolean:

Assume the array is arr and the target element is target

Loop traversal:

(arr, target) => {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] === target) {
      return true;
    }
  }
  return false;
}
Copy after login

Compatibility: es1

Equal algorithm: ===

indexOf:

(arr, target) => {
  return arr.indexOf(target) >= 0;
}
Copy after login

Compatibility: es5

Equality algorithm: ===

filter:

(arr, target) => {
  return arr.filter(el => el === target).length > 0;
}
Copy after login

Compatibility: es5

Equal algorithm: ===

some:

(arr, target) => {
  return arr.some(el => el === target);
}
Copy after login

Compatibility: es5

Equal algorithm: ===

find:

(arr, target) => {
  return arr.find(el => el === target) !== undefined;
}
Copy after login

Compatibility: es2015

Equal algorithm: ===

findIndex:

(arr, target) => {
  return arr.findIndex(el => el === target) >= 0;
}
Copy after login

Compatibility: es2015

Equal algorithm: == =

includes:

(arr, target) => {
  return arr.includes(target);
}
Copy after login

Compatibility: es2016

Equality algorithm: SameValueZero

==Tips:==

== The difference between = and SameValueZero is that
NaN === Nan => false and SameValueZero considers two NaNs to be equal. Please refer to MDN for details. If you want to change the implementation of === above into the implementation of SameValueZero, you can write:

el === target || (Object.is(el, NaN) && Object.is(target, NaN))
Copy after login

With es6 and babel so popular nowadays, most of the time we just use includes directly.

The above is the detailed content of How does js determine that an array contains specific elements? (Method summary). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template