LoginSignup
4
5

More than 5 years have passed since last update.

【JS】Object.definePropertyを使用して安全にArray.prototype.findIndexを追加する

Last updated at Posted at 2017-02-18

ECMAScript 2015(ES6)にはArray.prototype.findIndex関数が追加されています。すでにChrome等新しいブラウザでは使用できるようになっていますが、一部の古いブラウザやGoogle Apps Scriptでは未実装となっています。結構使用頻度が多いので、Array.prototypeに追加してみます。

コードは、ほとんどこのページのものなんですが、直接Array.prototype.findIndex = function...とか書いちゃうとプロトタイプ汚染させてしまうので、Object.definePropertyを使用しています。
(なお、プロトタイプ汚染についてはこのページが詳しいです。)

if (!Array.prototype.findIndex) {
  var findIndex = function(predicate) {
    if (this === null) {
      throw new TypeError('Array.prototype.findIndex called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return i;
      }
    }
    return -1;
  };

  Object.defineProperty(Array.prototype, 'findIndex', {
    enumerable: false,
    configurable: false,
    writable: false,
    value: findIndex,
  });
}

Javascriptは手軽に既存のオブジェクトを拡張できるのがいいですね〜。

参考

4
5
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
4
5