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