Home > Article > Web Front-end > Summarize several methods of traversing arrays in JavaScript
This article summarizes some methods for traversing arrays in javascript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
There are several ways to traverse an array, and they will be listed one by one below!
let index = 0; const array = [1, 2, 3, 4, 5]; while (index < array.length) { console.log(array[index]); index++; }
const array = [1,2,3,4,5]; for(let index=0;index<array.length;index++){ console.log(array[index]); } for(let index in array){ console.log(array[index]); }
const array=[1,2,3,4,5]; array.forEach(function(current_value,index,array){ console.log(`At index ${index} in array ${array} the value is ${current_value}`) })
The last construct is useful, but does not return a new array, which may be undesirable for your particular case. map solves this problem by applying a function to each element and then returning a new array.
const array = [1,2,3,4,5]; const square = x =>Math.pow(x,2); const squares = array.map(square); console.log(`${array}`); console.log(`${squares}`)
The reduce() method applies a function to the accumulator and each element in the array (from left to right) to Reduce to a single value
const array = [1,2,3,4,5]; const sum = (x,y) => x + y; const array_sum = array.reduce(sum,0); console.log(`the sum of arrray:${array} is ${array_sum}`);
Filter elements in the array based on a Boolean function
const array = [1,2,3,4,5]; const even = x => x%2 === 0; const even_array = array.filter(even); console.log(`even numbers in array ${array} : ${even_array}`);
I got an array and wanted to test whether each element meets the given condition
const array = [1,2,3,4,5,8]; const under_six = x => x<6; if(array.every(under_six)){ console.log(`every elemnet in the array is less than 6`); } else{ console.log(`at least one element in the array was bigger than 6`); }
Test whether At least one element matches the Boolean function
const array = [2,4,5,6,8]; const over_five = x => x>5; if(array.some(over_five)){ console.log(`at least one element bigger than 5 was found`); } else{ console.log(`no element bigger than 5 was found`); }
That’s it. If you have anything else, please add it!
Recommended related tutorials: JavaScript video tutorial
The above is the detailed content of Summarize several methods of traversing arrays in JavaScript. For more information, please follow other related articles on the PHP Chinese website!