Home >Web Front-end >JS Tutorial >How does js determine that an array contains specific elements? (Method summary)
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
(arr, target) => { for (var i = 0; i < arr.length; i++) { if (arr[i] === target) { return true; } } return false; }
Compatibility: es1
Equal algorithm: ===
(arr, target) => { return arr.indexOf(target) >= 0; }
Compatibility: es5
Equality algorithm: ===
(arr, target) => { return arr.filter(el => el === target).length > 0; }
Compatibility: es5
Equal algorithm: ===
(arr, target) => { return arr.some(el => el === target); }
Compatibility: es5
Equal algorithm: ===
(arr, target) => { return arr.find(el => el === target) !== undefined; }
Compatibility: es2015
Equal algorithm: ===
(arr, target) => { return arr.findIndex(el => el === target) >= 0; }
Compatibility: es2015
Equal algorithm: == =
(arr, target) => { return arr.includes(target); }
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))
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!