LoginSignup
3
0

More than 3 years have passed since last update.

javasqriptの便利メソッド等について

Last updated at Posted at 2020-02-09

初めに

現在、ES6のJavaScriptを学習しており、個人的なアウトプットとしたいと思います。

for分では考えることが多い?

まずはこちらを見てください。


const images = [
  { height: 10, width: 30 },
  { height: 20, width: 90 },
  { height: 54, width: 32 }
];
const areas = [];
for (i = 0; i < images.length; i++){
  areas.push(images[i].height * images[i].width)
}
console.log(areas) /* [300, 1800, 1728] */

こちらのfor文でやっていることはオブジェクトが入っているimagesという配列の数だけfor文内で繰り返しをしてareaという面積を求める処理です。

僕はfor文の中で考えることが多いなという印象があります。
・ imageがトータル数を数える。
・ i を ループするたびに足していく。
・ images[i].heightのところが長い。

上記が僕がこの処理の時に考えたり、感じていることです。。

map()を使ってみる

const images = [
  { height: 10, width: 30 },
  { height: 20, width: 90 },
  { height: 54, width: 32 }
];
const areas = images.map(function(image){
  return image.height * image.width /* [300, 1800, 1728] */
});

こちらはmap()を使っています。map()というのはコールバック関数を実行して配列の中の要素に対して好きな処理をして、結果を返り値として新しい配列を作成するといったものです。
for文お決まりの
for (i = 0; i < images.length; i++)
といったことがなくなってスッキリした印象があるのと、要素へアクセスするために添字を使っていないところもいいところなのかなと思っています。
ですがもう少しスッキリしたいですね。

アロー関数を使ってみる

const images = [
  { height: 10, width: 30 },
  { height: 20, width: 90 },
  { height: 54, width: 32 }
];
const areas = images.map(image =>image.height * image.width);
console.log(areas) /* [300, 1800, 1728] */

さらにスッキリして処理の内容が直感的に分かりやすくなった気がします。
ではもう少しいじってみます。

分割代入を使ってみる

const images = [
  { height: 10, width: 30 },
  { height: 20, width: 90 },
  { height: 54, width: 32 }
];
const areas = images.map(({height, width}) => height * width);
/* [300, 1800, 1728] */

これは分割代入というES6から登場した機能を使っているのですが少し難しいかもです。。
コールバック関数の引数となる部分に{height, width}というimagesのオブジェクト内の値を入れることができます。

最後に

最初のfor文に比べたら少しスッキリしましたね。今回は単純なプログラムなのですが、もっと複雑なプログラムを作る際には便利メソッド(forEach、some, map, every, find, some, reduce)などなどを使いこなせるかが鍵になっているのかなと思った今日この頃でございます。
何かもっとこうしたらとかアドバイスや誤った考え方があればご指摘ください。
よろしくお願いいたします。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0