JavaScript judges whether the elements in an array are all 0

       Why does the console log output frequently disappear?
  Why does the wxss code fail frequently? Why is
  the wxml layout in a mess?   Is  it the loss 
  of morality?


foreword

You can use the methods in JavaScript every()to determine whether the elements in an array are all 0. This method executes a given function on each element in the array, and returns true if the function returns true for each element.


text

Here is a sample code:

const arr = [0, 0, 0, 0];
const allZeros = arr.every(item => item === 0);

if (allZeros) {
  console.log('The array contains only zeros.');
} else {
  console.log('The array contains non-zero values.');
}

In this example, we first define an array containing multiple zeros. Then, we use every()the method and a callback function to check whether each element in the array is equal to 0. If all elements are equal to 0, every()the method will return true and we will print "The array contains only zeros." to the console. Otherwise, we output "The array contains non-zero values.". 


Summarize

Note that if any element in the array is not equal to 0, the every()method will immediately return false because it already knows that an element does not meet the condition.

Guess you like

Origin blog.csdn.net/m0_66016308/article/details/129287026
Recommended