website-template icon indicating copy to clipboard operation
website-template copied to clipboard

Fix: `Array.from()`を`[...]`に変更

Open manabuyasuda opened this issue 5 years ago • 2 comments

4.4 繰り返し可能なオブジェクトを配列に変換する場合はArray.fromの代わりにスプレッド構文...を使用すること。

https://github.com/mitsuruog/javascript-style-guide#arrays--from-iterable

manabuyasuda avatar May 02 '19 15:05 manabuyasuda

ただし、

4.6 繰り返し可能なオブジェクト(iterables)へのマッピングにはスプレッド構文...の代わりにArray.fromを使用すること。理由は中間配列の作成を防ぐためです。

// bad const baz = [...foo].map(bar);

// good const baz = Array.from(foo, bar);

とあるので、単純に[...]に変更するのではなく、map()filter()などで新しい配列を生成する場合はArray.from()にすると推測される。

manabuyasuda avatar May 02 '19 16:05 manabuyasuda

stBreadcrumbの以下の箇所をレストパラメータにしてもいいかなと思った。

    [...link].forEach(item => {
      const href = item.getAttribute('href').replace(/index\.html$/, '');
      const isMatchCurrentPage = href === path;

      if (isMatchCurrentPage) {
        item.setAttribute('aria-current', currentValue);
        item.setAttribute('tabindex', -1);
      }
    });

でも、以下のような関数がスコープごとに作られてしまう。 これが「中間配列の作成」なんだろうか?

_toConsumableArray(arr);
_nonIterableSpread();
_iterableToArray(iter);
_arrayWithoutHoles(arr);

Array.from() メソッドは、配列風オブジェクトや反復可能オブジェクトから、新しい、浅いコピーの Array インスタンスを生成します。

rest parameters とは、不特定多数の引数を配列として受け取る構文です。

MDNを見ていても、レストパラメータよりArray.from()の方が意図が明確な感じがする。

manabuyasuda avatar May 09 '19 10:05 manabuyasuda