function square(num) { console.log(num*num); } var num = [1,2,3,4,5]; num.forEach(square);//输出1,4,9,16,25
function isEven(num) { return num % 2 == 0; } var num = [2,4,6,8,10]; var even = num.every(isEven); if (even) { console.log("all numbers are even");//输出这条 } else { console.log("not all numbers are even"); }
function isEven(num) { return num % 2; } var num = [1,2,3,4,5,6,7,8,9,10]; var someEven = num.some(isEven); if (someEven) { console.log("some numbers are even");//输出这条 } else { console.log("no numbers are even"); } num = [1,3,5,7,9]; someEven = num.some(isEven); if (someEven) { console.log("some numbers are even"); } else { console.log("no numbers are even");//输出这条 }
function add(runningTotal, currentValue) { return runningTotal + currentValue; } var num = [1,2,3,4,5,6,7,8,9,10]; var sum = num.reduce(add); //其执行原理以下图所示 add(1,2);//3 add(3,3);//6 add(6,4);//10 add(10,5);//15 add(15,6);//21 add(21,7);//28 add(28,8);//36 add(36,9);//45 add(45,10);//55
reduce 方法也能够用来将数组中的元素链接成一个长的字符串数组
function concat(accumulatedString, item) { return accumulatedString + item; } var words = ["the ", "quick ", "brown ", "fox"]; var sentence = words.reduce(concat); console.log(sentence);//the quick brown fox;
JavaScript还提供了reduceRight() 方法,和reduce()方法不一样,它是从右到左执行。dom
function concat(accumulatedString, item) { return accumulatedString + item; } var word = ["the ", "quick ", "brown ", "fox"]; var sentence = word.reduceRight(concat); console.log(sentence);//" fox brown quick the";
function curve(grade) { return grade += 5; } var grades = [1,2,3,4,5]; var newGrades = grades.map(curve); console.log(newGrades);//6,7,8,9,10
function isEven(num) { return num % 2 == 0; } function isOdd(num) { return num % 2 != 0; } var num = []; for (var i = 0; i < 20; ++i) { num[i] = i + 1; } var evens = num.filter(isEven); console.log(evens);//2,4,6,8,10,12,14,16,18,20 var odds = num.filter(isOdd); console.log(odds);//1,3,5,7,9,11,13,15,17,19
下面是另外一个使用filter()方法的有趣案例(筛选出随机数中大于60的数)函数
function passing(num) { return num >= 60; } var grads = []; for (var i = 0; i < 20; ++i) { grads[i] = Math.floor(Math.random() * 101); } var passGrads = grads.filter(passing); console.log(grads); console.log(passGrads);
还能够使用filter()方法过滤字符串数组(过滤掉那些不包含“cie”的单词)ui
function afterc(str) { if (str.indexOf("cie") > -1) { return true; } return false; } var word = ["recieve","deceive","percieve","deceit","concieve"]; var misspelled = word.filter(afterc); console.log(misspelled);//recieve,percieve,convieve