本篇文章為大家總結了一些javascript遍歷陣列的幾種方法。有一定的參考價值,有需要的朋友可以參考一下,希望對大家有幫助。
有幾種方法可以遍歷數組,下面將逐一羅列!
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}`) })
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}`)
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}`);
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}`);
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`); }
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`); }
以上是總結javascript中遍歷數組的幾種方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!