How many elements are there in JavaScript query array 1

       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 Array.reduce() method in JavaScript to iterate over the array and compare each element with the target element to count the number of occurrences.


text

Here is a sample code:

const arr = [1, 0, 1, 0, 1, 1, 0];
const count = arr.reduce((acc, cur) => {
  return acc + (cur === 1 ? 1 : 0);
}, 0);
console.log(count); // 输出:4

In the above code, the first parameter of the reduce() method is a callback function, which receives two parameters: the accumulator (acc) and the current element (cur). In the callback function, if the current element is equal to the target element, add 1 to the accumulator; otherwise, return the original accumulator value. The second parameter of the reduce() method is the initial value, which is set to 0 here. 

After the above code is executed, the value of the count variable is the number of elements 1 in the array.

Array.reduce() is a prototype method of the Array type in JavaScript. It can be used to iterate the elements in the array and accumulate the iteration results into a single return value.

The reduce() method receives a callback function as a parameter, which can receive four parameters: the accumulator (accumulator), the current element (currentValue), the index of the current element (index) and the entire array (array). The callback function must return a value, which will be used as the value of the accumulator for the next iteration.

The following is an example code that uses the reduce() method to calculate the sum of all elements in an array:

const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((acc, cur) => {
  return acc + cur;
}, 0);
console.log(sum); // 输出:15

Summarize

In the above code, the callback function receives two parameters: the accumulator (acc) and the current element (cur), and the initial value of the accumulator is 0. In each iteration, the callback function adds the accumulator to the current element, uses the result as the accumulator value for the next iteration, and finally returns the final accumulator value. Since there are 5 elements in the array, the final accumulator value is 1 + 2 + 3 + 4 + 5 = 15.

Guess you like

Origin blog.csdn.net/m0_66016308/article/details/129299014