LoginSignup
0
0

More than 3 years have passed since last update.

JavascriptのforEachでindexの使用例

Posted at

forEachのindexとかarrayの使いどころがわからなかった

forEachでコールバック関数を利用するのみでindex,arrayを使ったことがなかった。
face-api.jsの中身を見ていてああ、なるほどと思ったのでまとめます。

face-api.jsの中で使われていたコードの雰囲気

test.js

array.slice(1).forEach(({ x, y }, index) =>
            {
                const from = array[index];
                ctx.moveTo(from.x, from.y);
                ctx.lineTo(x, y);
            })
ctx.stroke();
//~~~

これは顔の特徴点と特徴点同士を線でつなぎ、canvas上に描画する処理の一部。↓の青線を引く。
image.png

slice関数で1番目以外の点を取得し、それぞれについて一つ前の点から次の点へ直線を引くという流れです。

あとがき

いままで使える機会があったが、わざわざ別で変数を用意して繰り返しインクリメントさせる
という非常にスマートでない方法でやっていた。。。
apiの中身を見てみるといろいろと発見がある!

0
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
0
0