ikemonn's blog

技術ネタをちょこちょこと

【Underscore.js】_.containsを読んだ

jashkenas/underscore_.containsを読んだ。

概要

_.contains(list, value, [fromIndex])

listにvalueがあればtrueを返す。

_.contains([1, 2, 3], 3); // true

ソースコード

  _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
    if (!isArrayLike(obj)) obj = _.values(obj);
    if (typeof fromIndex != 'number' || guard) fromIndex = 0;
    return _.indexOf(obj, item, fromIndex) >= 0;
  };

_.indexOfの中で、===を用いて比較しているのでオブジェクトを比較しようとするときは注意。

参考

jashkenas/underscore