Home > Article > Web Front-end > Whether the elements used in js arrays can pass the test of the specified function
In the previous article, we learned how to use copyWithin() to copy a part of an array. Please see "How to use copyWithin() in js to copy a part of an array". This time we will learn how to test whether an element can pass the specified function test. You can refer to it if necessary.
This time we have a small question. How about we do the math together?
Please read the question:
We have an array with ten elements: 2, 7, 9, 13, 78, 57, 91, 575, 765, 23. Now we Want to know if all the elements in this array are greater than 50? If yes please return true, if not please return false.
<script> const isBelowThreshold = (currentValue) => currentValue > 50; var arr = new Array(2,7,9,13,78,57,91,575,765,23); console.log(arr.every(isBelowThreshold)); </script>
The result of this small example is
When we look at this example, when this question comes out, we know that the answer must be It is false. After all, there are elements 2, 7, 9, and 13 in the array, so it will definitely not pass the test.
Then let’s analyze it. In fact, there is nothing else to analyze. The main thing is the every
method. Let’s take a look.
The every() method tests whether all elements in the array can pass the test of the specified function. It returns a boolean value. The
every method executes the callback
function once for each element in the array until the element that causes the callback to return false
is found. If such an element is found, the every method will immediately return false. Otherwise, the callback will return true
for each element, and true for each element. The callback will only be called for allocated indexes. It is not called for indexes that have been dropped or never allocated.
When calling callback, you can pass in three parameters: element value, element index and original array.
It should be noted that:
If an empty array is received, this method will return true
in all cases.
Let’s take a look at the syntax structure of this method.
数组名称.every(callback(用于测试的当前值,当前值的索引,当前数组),执行函数时使用的this值)
That’s all. If you need it, you can read: javascript advanced tutorial
The above is the detailed content of Whether the elements used in js arrays can pass the test of the specified function. For more information, please follow other related articles on the PHP Chinese website!