LoginSignup
3
3

More than 5 years have passed since last update.

CoffeeScriptで配列の連結

Last updated at Posted at 2015-03-18

配列でa + bはできないけど、[a..., b...]は可能で、読みやすいというメモです。(個人差あり)

普通の方法

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]

という配列があったとして、連結しようとすると

d = a.concat b, c # [1, 2, 3, 4, 5, 6, 7, 8, 9]

となってしまい、若干のロジック感が気になっていました。

splat演算子が使えるじゃないか

ところが、CoffeeScript Cookbookを眺めていて、

d = [a..., b..., c...] # [1, 2, 3, 4, 5, 6, 7, 8, 9]

が可能なことに気づいたのでした。

ただし、書き出されるJavaScriptが、

var d, slice = [].slice;

d = slice.call(a).concat(slice.call(b), slice.call(c));

のようになるので、本番に入れて良いのかなーという気はしないでもなし。

gulpで使うと良さげ

gulpの設定ファイルとかだといい感じ。

$ =
  js: ['./src/app.js', './src/lib/**/*.js']
  components: ['./src/components/*.html']

gulp.task 'watch', ->
  browserSync.init
  gulp.watch [$.js..., $.components...], ['browserify']
3
3
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
3
3