js配列のローズマリーメソッド(some、every、forEach、map、filter)
6826 ワード
// ( )
// 、
//1、forEach ( )
function square(num){
alert(num * num) ;
}
var nums = [1,2,3,4,5];
console.log(nums.forEach(square));
//2、every ( , )
function isEven (num) {
return num % 2==0;
}
var evens=[2,4,6,8,10];
var isAllEven = evens.every(isEven); // ,every
if(isAllEven){
alert("all is even");
}else{
alert("not all is even");
}
//3、some ( ,some )
var nums = [1,2,3,5,7,9];
function isEven (num) {
return num % 2==0;
}
alert(nums.some(isEven)); //true
//4.reduce
// :
function add (currentTotal,currentValue) {
//alert(currentValue);
//alert(currentTotal);
return currentTotal+currentValue;
}
var nums = [1,2,3,4,5,6,7];
alert(nums.reduce(add));
// :
function linkStr (foreStr,currentStr) {
return foreStr + currentStr;
}
var strings = ["nolan","is","studying","javascript"];
alert(strings.reduce(linkStr));
// 、
//1.map ( forEach )
// :
function firstAlpha (word) {
return word[0].toUpperCase();
}
var words = ["nolan","is","studying","javascript"];
var firstAlphas = words.map(firstAlpha);
alert(firstAlphas.join("")); // join
//2.filter ( every )
// : ( true)
function isEven (num) {
return num % 2==0;
}
var nums=[1,2,4,6,8,10];
var evens = nums.filter(isEven);
alert(evens);
// : ,
function pass (grade) {
if(grade>60){
return true;
}else{
return false;
}
}
var grades = [];
for(var i=0;i<20;i++){
grades[i]=Math.floor(Math.random()*101);
}
alert(grades);
var passedGrades=grades.filter(pass);
alert(passedGrades);