In the previous article, we learned about how elements execute specified functions. Please see "How elements in js arrays execute specified functions". This time we will learn about the method of using includes() to determine whether an array contains a specified value. You can refer to it if necessary.
This time we will look at a small problem first:
It is known that we have an array containing one, two, and three. We want to know whether this array contains the element five. What to do? Returns true if included, false if not included. So what if the element we want to know is one? Included or not?
<script> var arr = new Array(7); arr[0] = "one"; arr[1] = "two"; arr[2] = "three"; console.log(arr.includes("five")); console.log(arr.includes("one")); </script>
The result of this small problem is
In this small problem, we can see that in this array, only one is included , two, three, do not contain five, so when judging that the array package does not contain five, you can clearly see that the result is false; and when judging that the array package does not contain one, you can see that the result is true.
After knowing this, let’s take a look at this method.
includes() method is used to determine whether an array contains a specified value. Depending on the situation, it returns true if it contains, otherwise it returns false.
Let’s take a look at the syntax format of this method.
数组名称.includes(需要查找的元素值,从哪里开始查找)
It should be noted that:
When using includes() to compare strings and characters, it is case-sensitive.
If the second parameter of this method is a negative value, the search starts from the index of "array.length search position" in ascending order (even if it jumps forward from the end to the absolute value index of the search position, then Search later). Default is 0. If the value at the search position is greater than or equal to the length of the array, false is returned and the array is not searched.
If the value of the search position is negative, the calculated index will be used as the position to start searching for searchElement. If the calculated index is less than 0, the entire array is searched.
That’s all. If you need it, you can read: javascript advanced tutorial
The above is the detailed content of How to use includes() in js to determine whether an array contains a specified value. For more information, please follow other related articles on the PHP Chinese website!