Home  >  Article  >  Web Front-end  >  How to determine whether an element in an array passes the test in js

How to determine whether an element in an array passes the test in js

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-08-12 11:53:181987browse

In the previous article, we learned how to achieve the cumulative effect of elements in an array. Please see "How to achieve the cumulative effect of elements in js array". This time we will learn about the method of determining whether an element in an array passes the test. You can refer to it if necessary.

We now have such a problem. It is known that there is an array containing 7, 2, 5, 14, 8. Now we want to know that in this array, when the elements we contain are divided by 2, Whether there is an element that can be divided evenly, if so please return true, if not please return false.

<script>
var arr = new Array(7);
arr[0] = 7;
arr[1] = 2;
arr[2] = 5;
arr[3] = 14;
arr[4] = 8;
console.log(arr);
const even = (element) => element % 2 === 0;
console.log(arr.some(even));
</script>

The result of this small example is

How to determine whether an element in an array passes the test in js

We can see that the result of this small example is true, which means that in this array at least There is an element that is divisible by 2. You can take a look at this question. In this question, we can easily know that 2 is divisible by 2, 14 is also divisible by 2, and 8 is also divisible by 2, so this result must be true.

After understanding so much, let’s take a look at some method.

some() method tests whether at least one element in the array passes the provided function test. It returns a Boolean value. If at least one element in the array passes the test of the callback function, it will return true; if all elements fail the test of the callback function, the return value will be false.

The syntax format of this method is

arr.some(callback(正在处理的元素,正在处理的元素,被调用的数组),执行函数时使用的值)

some()Execute the callback function once for each element in the array until Find a value that causes the callback to return a "true value" (that is, a value that can be converted to a boolean true). If such a value is found, some() will immediately return true. Otherwise, some() returns false. callback will only be called on indexes that have a value, not on indexes that have been deleted or have never been assigned a value.

That’s all. If you need it, you can read: javascript advanced tutorial

The above is the detailed content of How to determine whether an element in an array passes the test in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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