LoginSignup
31

More than 5 years have passed since last update.

underscore.js入門

Last updated at Posted at 2012-12-26

Backbone.js Advent Calendar 4日目

参加はこちらから! http://atnd.org/events/22017

Backbone.jsはunderscore.jsというものに(唯一)依存しており,利用する場合はunderscore.jsもロードしてやらなければなりません.
ではこのunderscore.jsとは何なのかというと,配列操作やオブジェクト処理に便利な関数群を提供するライブラリです.ざっくり言うと配列や連想配列などがRubyっぽい形で操作できるようになります.

使い方

underscore.jsはロードすると_を定義します.使い方は以下の2通りです.

  • _を関数として利用する
    • 例: _.each(array, function(element) { ... });
  • オブジェクト指向的につかい,対象オブジェクトをラップしてメソッドを利用する
    • 例: _(array).each(function(element) { ... });

Rubyに慣れている人ならかなり書き易く感じると思います.
以下いくつか便利な関数の利用方法

each

_({a:1, b:2, c:3}).each(function(v,k) { console.log("key: " + k + ", value: " + v); })
// key: a, value: 1
// key: b, value: 2
// key: c, value: 3

tap

_([1,2,3]).chain().tap(console.log).map(function(n){ return n * 3; }).value();
// [1, 2, 3] (console.logで表示される)
// [3, 6, 9] (全体の返り値)

以上,簡単でしたがunderscore.jsの便利さが伝われば嬉しいです.
その他underscore.jsで提供される関数についてはドキュメントを.http://documentcloud.github.com/underscore/

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
31