6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

IE11で使用できないJavaScriptの記法

Last updated at Posted at 2020-10-22

背景

何も気にせずJavaScriptを書いていたらIEで正しく動作しないものにいくつか当たったので、エラー内容とその修正方法を記録します。

メソッド記法

エラー内容

SCRIPT1002: 構文エラーです。

原因

const question = {
  getAnswer() {
    console.log('回答だよ');
  }
}

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Functions/Method_definitions
メソッド定義の短い構文はIEでは使えない。

解決方法

const question = {
  getAnswer: function() {
    console.log('回答だよ');
  }
}

functionを省略しない。

テンプレート文字列

エラー内容

SCRIOPT1014: 文字が正しくありません。

原因

const massage = `メッセージは${text}です。`

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Template_literals
バッククォートを使用した記法はIEではできない。

解決方法


const message = 'メッセージは' + text + 'です。'

for...of

エラー内容

SCRIPT1004: ‘:’ がありません。

原因

for (let answer of Answers) {
  console.log(answer);
}

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Statements/for...of
for...ofを使った配列のループはIEではできない。

解決方法

for (let i=0; i < Answers.length; i++) {
  const answer = Answers[i]
  console.log(answer);
}

アロー関数

エラー内容

SCRIPT1002: 構文エラーです。

原因

element.addEventListener('click', () => {
  console.log('クリックされたよ');
};

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Functions/Arrow_functions
アロー関数でのfunctionの省略はできない。

解決方法

element.addEventListener('click', function() {
  console.log('クリックされたよ');
};

NodeListに対するforEach

エラー内容

SCRIPT438: オブジェクトは 'forEach' プロパティまたはメソッドをサポートしていません。

原因

element = document.querySelectorAll('.test');
element.forEach(function (item) {
  console.log(item);
};

https://developer.mozilla.org/ja/docs/Web/API/Document/querySelectorAll
querySelectorAll()メソッドはNodeListを返す。

https://developer.mozilla.org/ja/docs/Web/API/NodeList/forEach
IEではNodeListに対するforEachはサポートしていないのでエラーになる。

解決方法

elementNodeList = document.querySelectorAll('.test');
// Arrayに変換している
element = Array.prototype.slice.call(elementNodeList, 0);
element.forEach(function (item) {
  console.log(item);
};

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
Arrayに対するforEachはIEでも使用できる。のでArrayに変換してからforEachを使用。

他にもいくつかの解決方法があるらしい。

まとめ

解決方法は一例です。
正しく動かない記法はまだまだあると思いますが、自分が使用した段階で追加します。
IEで正しく動かないJavaScriptについてのまとめ記事は探すとたくさん出てくるので、困った際はエラー文でググると、すぐに原因が見つけられると思います。

参考記事

6
2
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
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?