【備忘録】IE8でreduceが動かない!?そんなときはこれを使え!!

こんにちは。RABIMAX管理人、らびです。
今回から私の備忘録ということで使ったコード、便利だったものもちょくちょくのせていこうと思います。

今回使用した、reduceタグですが、reduceタグ自体の説明は省略させていただきます!
なんやねん!って方はぐぐってくださいね!

で、今回つまったのはにっくき、IE8ぱいせんが、
IE8< reduce?聞いたことねぇなぁ、エラーにしたろ
って感じで動いてくれませんでした!

解決策はとっても簡単、下記のコードをコピペして使用するだけでいけました!!


if (!Array.prototype.reduce) {
  Array.prototype.reduce = function reduce(accumulator){
    if (this===null || this===undefined) throw new TypeError("Object is null or undefined");
 
    var i = 0, l = this.length >> 0, curr;
 
    if(typeof accumulator !== "function") 
// ES5 : "If IsCallable(callbackfn) is false, throw a TypeError exception."
      throw new TypeError("First argument is not callable");
 
    if(arguments.length < 2) {
      if (l === 0) throw new TypeError("Array length is 0 and no second argument");
      curr = this[0];
      i = 1; // start accumulating at the second element
    }
    else
      curr = arguments[1];
 
    while (i < l) {
      if(i in this) curr = accumulator.call(undefined, curr, this[i], i, this);
      ++i;
    }
 
    return curr;
  };
}


コピペして使ってみてください!
IE8< おっ、reduceやんけ、知ってる知ってる
となって動きます!!

以上RABIMAX管理人、らびでしたー!

コメント

タイトルとURLをコピーしました