0
0

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 3 years have passed since last update.

[備忘録]JavaScritptでRange配列を作る

Posted at

以下の結果はすべて同じになるので

console.log(
  Array.from({ length: 10 }).map((_, index) => index)
);

console.log(
  Array.from({ length: 10 }, (_, index) => index)
);

console.log(
  [...Array(10).keys()]
);
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

上記のどれかを使って以下のようなRange関数がつくれる。

function range(start, end) {
  return Array.from({ length: end })
    .map((_, index) => index + 1)
    .filter((num) => num >= start && num <= end);
}

console.log(range(2, 8));
[2, 3, 4, 5, 6, 7, 8]
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?