Get the App
SLTechnology News&Howtos  ›  Development  › 

How to determine whether an element satisfies a given condition by JS array

Shulou Source: shulou.com Published: 2022-06-03 17:40:21 10月19日 Update

This article mainly introduces how JS array judges whether the elements meet the given conditions, has a certain reference value, interested friends can refer to, I hope you have a lot of gains after reading this article, let Xiaobian take you to understand.

1. Use the for statement to traverse the array and check whether the elements in the array are even.

var a = [2,4,5,6,8],b=0;for(var i=0;i if (a[i] % 2 != 0) { b=0 break; }else{ b++; }}if (b) { console.log("all even");} else { console.log("not all even");}

Using some() methods, you can detect whether there are elements in the array that meet the conditions.

Thinking differently, it can also be used to check whether all elements in the array do not meet the specified conditions. If they do not meet the specified conditions, it will return false, and if one or more match, it will return true.

function f(value, index, ar) { if (value % 2 != 0) { return true; }}var a = [2,4,6,8,10,12];var b = a.some(f);if (b) { console.log("not all even");} else { console.log("all even numbers");} Thank you for reading this article carefully. I hope that the article "How JS Array Determines whether an Element satisfies a given condition" shared by Xiaobian will be helpful to everyone. At the same time, I hope that everyone will support it a lot. Pay attention to the industry information channel. More relevant knowledge is waiting for you to learn!

Tags: Array element even number condition article test value interest at the same time multiple method more friend knowledge ribbon industry angle sentence information information channel Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi NVidia vpn Shulou Technology Redmi