JS的数组迭代方法

<!doctype html> <html> <head lang="zh"> <meta charset="utf-8"> <title>js数组迭代</title> <meta content="webkit"> <script> var arr1 = [1,2,3,4,5,6]; function double(x){ return 2*x; } // map可以产生一个新的数组 // alert(arr1.map(double)); function print(x){ console.log(x*2) } arr1.forEach(print); function even(x){ return x %2 ==0 } var arr2 = [2,4,,5,6]; // alert(arr2.every(even))//false; // alert(arr2.some(even))//true; function add(a,b){ return a*b; } var arr3=[1,2,4,5]; var factorial = arr3.reduce(add); //alert(factorial) //40 var arr4=[1,24,5,6,7,8,234,4]; alert(arr4.filter(even)) </script> <pre> map,filter可以产生一个新的数组 var arr1 = [1,2,3,4,5,6]; function double(x){ return 2*x; } //alert(arr1.map(double)); //forEach是对数组每项都调用某个函数,不返回 function print(x){ console.log(x*2) } arr1.forEach(print); //some,every 参数是一个有返回布尔值的函数 function even(x){ return x %2 ==0 } var arr2 = [2,4,,5,6]; // alert(arr2.every(even))//false; // alert(arr2.some(even))//true; //reduce接受一个函数,返回一个值 ,不断累加到最后一项 //同理,reduceRight是由后面累加到第一项,具体可从CONCAT 看出 function add(a,b){ return a*b; } var arr3=[1,2,4,5]; var factorial = arr3.reduce(add); //alert(factorial) //40 //filter与every类似,参入一个返回布尔值 的函数,返回一个新的数组 </pre> </body> </html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgfxss.html