Javascript Method Summary for Determining whether an Array Contains Specific Elements

  array, javascript

Judging whether an array contains a specific element is a very common requirement. javascript has many implementation methods. Today, if you are free to summarize it, it will be sorted by compatibility from strong to weak. The return type is always boolean:

Suppose 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;
}

Compatibility: es1

Equality algorithm: = = =

indexOf:

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

Compatibility: es5

Equality algorithm: = = =

filter:

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

Compatibility: es5

Equality algorithm: = = =

some:

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

Compatibility: es5

Equality algorithm: = = =

find:

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

Compatibility: es2015

Equality algorithm: = = =

findIndex:

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

Compatibility: es2015

Equality algorithm: = = =

includes:

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

Compatibility: es2016

Equality algorithm: SameValueZero

==Tips:==

= = = The difference from SameValueZero is that
NaN === Nan => falseSameValueZero thinks that the two nans are equal. For details, please refer toMDN. If you want to change the above = = = implementation into a SameValueZero implementation, you can write:

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

With es6 and babel so popular nowadays, we use them directly most of the time.includesJust do it.

Thank you for reading. In addition, I’m here to help my friends raise funds for love. I hope everyone can give some love. My friend’s mother is suffering from rectal cancer. She is currently receiving treatment in Beijing Armed Police General Hospital. Please leave a message and leave your contact information. Thank you in the future!

clipboard.png