示例代碼以下:javascript
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>map</title> </head> <body> <script> var arr = [1,2,3,4]; var resultArr = arr.map(function(item){ return item*2 }); console.log(arr,resultArr); </script> </body> </html>
測試地址html
示例代碼以下:java
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>reduce</title> </head> <body> <script> /* *注:reduce默認有三個參數,第一個參數是每一次求值的結果值(初始等於數組第一項), *第二個參數是下一項要計算的項,第三個值爲第二個參數在數組中的索引 */ var arr = [60,20,31,54]; //求數組各項和 var result = arr.reduce(function(temp,next,index){ return temp+next; }); //求平均值 var result0 = arr.reduce(function(temp,next,index){ if(index < arr.length-1){ return temp + next; }else{ return (temp+next) / arr.length; } }) console.log(arr,result,result0); </script> </body> </html>
測試地址數組
示例代碼以下:函數
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>filter</title> </head> <body> <script> /* *注:根據函數的返回值的真假來決定當前項需不須要放入要返回的新數組中 *itme就是數組的每一項的值,若是return爲空則把當前item放入返回的數組中 */ var arr = [1,2,3,5,8,4]; //取出數組中的偶數項 var resultArr = arr.filter(function(item){ return item % 2 === 0; }) console.log(arr,resultArr); </script> </body> </html>
測試地址測試
示例代碼以下:code
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>forEach</title> </head> <body> <script> /* *對數組執行遍歷,其中三個參數依次爲當前遍歷到的項,當前項的索引,和被遍歷的數組自己 */ var arr = [1,2,3,4]; arr.forEach(function(item,index,arr){ console.log(item,index,arr); }) </script> </body> </html>