JS 陣列遍歷你知道幾種?
阿新 • • 發佈:2019-08-28
for迴圈?好像是聽說這是菜鳥一貫作風(抱頭瑟瑟發抖... ...)
但是你知道幾種?往下看,歡迎補充~
1、for迴圈,為了證明我不要當菜鳥的決心,我就直接跳過,連揮手都來不及的那種。
。。。 。。。
2、forEach迴圈,迴圈陣列中每一個元素並採取操作, 沒有返回值, 可以不用知道陣列長度。
返回值:無
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <title>forEach方法</title> </head> <body> <script type="text/javascript"> var arr = [6, 5, 4]; var total = 0; arr.forEach(function(value, index, arr) { console.log('當前值:' + value); console.log('當前值對應的索引:' + index); console.log('原陣列:' + arr); total += value }); console.log(total); </script> </body> </html>
輸出:
3、map函式,遍歷陣列每個元素,並回調操作,需要返回值,返回值組成新的陣列,原陣列不變。
返回值:返回按返回值生成的新陣列
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <title>map方法</title> </head> <body> <script type="text/javascript"> var arr = [6, 5, 4]; var arrNew = []; arrNew = arr.map(function(value, index, arr) { console.log('當前值:' + value); console.log('當前值對應的索引:' + index); console.log('原陣列:' + arr); return value * value }); //map返回新陣列 console.log(arrNew); </script> </body> </html>
輸出:
4、filter函式, 過濾通過條件的元素組成一個新陣列, 原陣列不變
返回值:返回過濾條件生成的新陣列
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <title>filter方法</title> </head> <body> <script type="text/javascript"> var arr = [6, 5, 4]; var arrNew = []; arrNew = arr.filter(function(value, index, arr) { console.log('當前值:' + value); console.log('當前值對應的索引:' + index); console.log('原陣列:' + arr); return value % 2 == 0; }); //map返回新陣列 console.log(arrNew); </script> </body> </html>
輸出:
5、some函式,遍歷陣列中是否有符合條件的元素,返回Boolean值
返回值:返回Boolean值,是否含有符合條件的元素
6、every函式, 遍歷陣列中是否每個元素都符合條件, 返回Boolean值
返回值:返回Boolean值,是否全部符合條件的元素
7、恭喜你。魂環增加一級,可