Help us understand the problem. What is going on with this article?

もうforループなんていらない!? その1 forEach, map, filter, find

More than 1 year has passed since last update.

JavaScriptの勉強を初めて1週間。
アウトプットすることで最速最短で最高のエンジニアになれると聞いて早速アウトプットしてみます!
今回は「forEach, map, filter, find」の4つについてまとめました。

その2はこちら【もうforループなんていらない!?その2every,some,reduce ついでにアロー関数とlet,constも】

forEach

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

与えられた関数を、配列の各要素に対して1度ずつ実行する。

var animals = ["micropig", "lion", "dog"];

animals.forEach(function(animal){
    console.log(animal);
});
 //
 //micropig
 //lion
 //dog
 //

map

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/map

与えられた関数を配列の各要素に対して1度ずつ実行し、新しい配列を生成する。元の配列はそのまま。

var numbers = [1,3,5,7];

var doubled = numbers.map(function(number){
    return number * 2;
});
console.log(numbers); //[1,3,5,7]
console.log(doubled); //[2,6,10,14]

filter

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

条件に合うものだけを抽出し、新しい配列を生成する。

var pigs = [ 
    {name:"pig", weight: 300}, 
    {name:"minipig", weight: 60},
    {name:"micropig", weight: 30}
];

var lightPigs = pigs.filter(function(pig){
    return pig.weight < 100;
});

console.log(lightPigs);
// 0: {name: "minipig", weight: 60}
// 1: {name: "micropig", weight: 30}

find

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/find

配列の要素の中で、1番最初に条件にあった値を返す。残りは検索されない。

var numbers = [65,48,34,160,98,10,4];

var found = numbers.find(function(number){
    return number < 50;
});

console.log(found); // 48
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away