1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【JavaScript】配列を任意の数列で初期化

Last updated at Posted at 2019-03-21

関数として数列を定義して、その数列を配列として初期化したいときの効率的な書き方です。

function f(n) {
  return 2 ** (n + 1) - 1;
}

例として2のべき乗から1を引いたメルセンヌ数の数列を定義しました。

これをよくやる方法で初期化してみます。

new-array-1.js
function f(n) {
  return 2 ** (n + 1) - 1;
}

const a1 = new Array(10);
for (let n = 0; n < 10; n++) {
  a1[n] = f(n);
}

console.log(a1);
// => [1, 3, 7, 15, 31, 63, 127, 255, 511, 1023]

可読性は高いのでこれでもいいのですが、ワンライナーで書く方法を思いつきました。

new-array-2.js
function f(n) {
  return 2 ** (n + 1) - 1;
}

const a2 = Array.from(Array(10), (_, n) => f(n));
console.log(a2);
// => [1, 3, 7, 15, 31, 63, 127, 255, 511, 1023]

Array.from で渡す関数の第2引数には Array.mapArray.forEach 同様配列のインデックスが渡るので、それを応用しました。

参考

1
1
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?