LoginSignup
1
1

More than 5 years have passed since last update.

Underscore.js に each_with_index を mixin する

Last updated at Posted at 2014-12-05

Qiita 初投稿です。

each_with_index とは

Ruby には each_with_index というメソッドがあります。
each に似ていますが、イテレータにインデクスも渡すところが異なります。

%w(foo bar baz).each_with_index {|s,i| puts "#{i}:#{s}"}

上のコードを実行すると以下のようになります。

0:foo
1:bar
2:baz

Underscore.js に mixin してみる

Underscore.js には each_with_index が無いようなので mixin してみました。
(※ vzvu3k6k さんからご指摘いただきました。each に渡すイテレータは第二引数で インデクスが取れるそうです。これは each_with_index と同様の動作です)

以下、コーディングは CoffeeScript でしています。

_.mixin
  each_with_index : (list, iterator) ->
      _(list.length).times (i) -> iterator list[i], i
      list

試してみます。

_.each_with_index ["foo","bar","baz"], (s,i) -> console.log i + ":" + s

コンソールに以下のように出力されました。

0:foo
1:bar
2:baz

うまくいったようです。

1
1
2

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