LoginSignup
3
2

More than 5 years have passed since last update.

JavaScript で n を与えて 1からn までの配列を作る

Last updated at Posted at 2017-12-18

Ruby の 1...4 みたいなことがしたくて、JavaScript で作る場合どうするか考えてみた。

> Array.from({length: 4}, (_, i) => i+1)
[ 1, 2, 3, 4 ]

ちなみに下記でもできる(バージョンにより挙動が不安定なので非推奨)

> [...new Array(4)].map( (_,i) => i );
[ 0, 1, 2, 3 ]
> new Array(4).map( (_,i) => i );
[ , , , ,  ]

参考

Array.from()のリファレンス
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/from

3
2
5

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
2