mapやfilterなどJavaScriptの配列に関するメソッド(まとめ)
JavaScriptにはmapやfilterなど配列に関する便利なメソッドがあります。
これらについて簡単にまとめてみました。
map
配列の各要素についてそれぞれ処理をして新しい配列を返します。
a = [1, 2, 3, 4, 5];
console.log(map_test(a));//[1, 4, 9, 16, 25]
function map_test(a) {
return a.map(function (x) {
return x * x;
});
}
console.log(map_test(a));//[1, 4, 9, 16, 25]
function map_test(a) {
return a.map(function (x) {
return x * x;
});
}
filter
配列の各要素について条件に合致するものだけを抽出した新しい配列を返します。
a = [1, 2, 3, 4, 5];
console.log(filter_test(a));//[1, 3, 5]
function filter_test(a) {
return a.filter(function (x) {
return x % 2 == 1;
});
}
console.log(filter_test(a));//[1, 3, 5]
function filter_test(a) {
return a.filter(function (x) {
return x % 2 == 1;
});
}
reduce
配列の各要素を最初から順に2個ずつ取り出して処理をして値を返します。合計や階乗などに使えます。
a = [1, 2, 3, 4, 5];
console.log(reduce_test(a));//15
function reduce_test(a) {
return a.reduce(function (x, y) {
return x + y;
});
}
console.log(reduce_test(a));//15
function reduce_test(a) {
return a.reduce(function (x, y) {
return x + y;
});
}
every
配列の各要素について条件に合致するかチェックし、全てが合致する場合、trueを返します。
a = [1, 2, 3, 4, 5];//false
console.log(every_test(a));
a = [4, 5];
console.log(every_test(a));//true
function every_test(a) {
return a.every(function (x) {
return x > 3;
});
}
console.log(every_test(a));
a = [4, 5];
console.log(every_test(a));//true
function every_test(a) {
return a.every(function (x) {
return x > 3;
});
}
some
配列の各要素について条件に合致するかチェックし、どれかが合致する場合、trueを返します。
a = [1, 2, 3, 4, 5];
console.log(some_test(a));//true
a = [4, 5];
console.log(some_test(a));//false
function some_test(a) {
return a.some(function (x) {
return x < 3;
});
}
console.log(some_test(a));//true
a = [4, 5];
console.log(some_test(a));//false
function some_test(a) {
return a.some(function (x) {
return x < 3;
});
}
forEach
配列の各要素について処理をします。
a = [1, 2, 3, 4, 5];
console.log(forEach_test(a));//1:4:9:16:25
function forEach_test(a) {
texts=[];
a.forEach(function (x) {
texts.push(x * x);
});
return texts.join(":");
}
console.log(forEach_test(a));//1:4:9:16:25
function forEach_test(a) {
texts=[];
a.forEach(function (x) {
texts.push(x * x);
});
return texts.join(":");
}
[ 2017年1月24日 | カテゴリー: JavaScript | タグ: まとめ , 配列 ]
コメントを残す