8
8

More than 5 years have passed since last update.

IE8 を Array:indexOf に対応させる

Posted at

JavaScript の indexOf 。
これ、IE8 では文字列のみに対応していて、配列の要素数を取得するメソッドは実装されていません。

indexOf メソッド (Array) (JavaScript)

このせいで IE8 で動かない Gem が出てきて困ったことになったので、CoffeeScript で解決しました。

array_index_of.coffee
unless "indexOf" of Array::
  Array::indexOf = (find, i) ->
    i = 0  if i is `undefined`
    i += @length  if i < 0
    i = 0  if i < 0
    n = @length

    while i < n
      return i  if i of this and this[i] is find
      i++
    -1

展開されると以下のようなコードになります。

array_index_of.js
(function() {

  if (!("indexOf" in Array.prototype)) {
    Array.prototype.indexOf = function(find, i) {
      var n;
      if (i === undefined) i = 0;
      if (i < 0) i += this.length;
      if (i < 0) i = 0;
      n = this.length;
      while (i < n) {
        if (i in this && this[i] === find) return i;
        i++;
      }
      return -1;
    };
  }

}).call(this);

こいつを assets/shared/ に放り込んでおき、application.js.erb で読み込みます。
位置は Array:IndexOf を使用しているJSより前である必要があります。先頭でもいいくらいかな?

application.js.erb
//= require shared/array_index_of
//= require jquery
    :

ネタ元はこちら。
Problem with Internet Explorer 8 ..

Client Side Validations は読んでそのまま、入力フォームのヴァリデーションをユーザが submit ボタンを押す前にクライアントサイドで実行できる優れものですが、IE8 はすでにサポート対象外になっています。
とはいうものの優しいコミッタさんが IE8 でも動くようにしてくれる CoffeeScript 教えてくれたり、IE8 互換に修正してくれたり、なんとかしてくれているようですね。

8
8
1

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
8
8