IE 11で実行されていないコードはChromeで正常に動作します


156

次のコードはChromeでは問題なく実行できますが、Internet Explorer 11では次のエラーをスローします。

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

要素のIDを変数に格納しています。どうした?

function changeClass(elId) {
  var array = document.getElementsByTagName('td');
  
  for (var a = 0; a < array.length; a++) {
    var str = array[a].id;
    
    if (str.startsWith('REP')) {
      if (str == elId) {
        array[a].style.backgroundColor = "Blue";
        array[a].style.color = "white";
      } else {
        array[a].style.backgroundColor = "";
        array[a].style.color = "";
      }
    } else if (str.startsWith('D')) {
      if (str == elId) {
        array[a].style.backgroundColor = "Blue";
        array[a].style.color = "white";
      } else {
        array[a].style.backgroundColor = "";
        array[a].style.color = "";
      }
    }
  }
}
<table>
  <tr>
    <td id="REP1" onclick="changeClass('REP1');">REPS</td>
    <td id="td1">&nbsp;</td>
  </tr>
  <tr>
    <td id="td1">&nbsp;</td>
    <td id="D1" onclick="changeClass('D1');">Doors</td>
  </tr>
  <tr>
    <td id="td1">&nbsp;</td>
    <td id="D12" onclick="changeClass('D12');">Doors</td>
  </tr>
</table>


9
str.indexOf("REP") == 0代わりにIE を使用する必要があるでしょう。
グラントトーマス

1
ES6はまだ標準ではありませんkangax.github.io/compat-table/es6の移行を支援するES6シムのライブラリがあるgithub.com/paulmillr/es6-shim(すべてがshimmableでないを含む)ES5のためのようなだけでは
Xotic750

回答:


320

String.prototype.startsWith JavaScriptの最新バージョンであるES6の標準メソッドです。

以下の互換性の表を見ると、Internet Explorerのバージョンを除く、現在のすべての主要なプラットフォームでサポートされていることがわかります。

╔═══════════════╦════════╦═════════╦═══════╦═══════════════════╦═══════╦════════╗
    Feature     Chrome  Firefox  Edge   Internet Explorer  Opera  Safari 
╠═══════════════╬════════╬═════════╬═══════╬═══════════════════╬═══════╬════════╣
 Basic Support     41+      17+  (Yes)  No Support            28       9 
╚═══════════════╩════════╩═════════╩═══════╩═══════════════════╩═══════╩════════╝

.startsWith自分で実装する必要があります。これがポリフィルです:

if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(searchString, position) {
    position = position || 0;
    return this.indexOf(searchString, position) === position;
  };
}

3
MDN web docsに 別の実装がありますString.prototype.startsWith = function(search, pos) { return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; };
oCcSking

1
@Okaによって与えられた最初の実装の傾向があります。追加の絞り込みと同様に、「position」が本当に数値であるかどうかをテストする場合があります。position=!isNaN(parseInt(position))?位置:0;
ErnestV

36

text.indexOf("newString")の代わりにが最善の方法ですstartsWith

例:

var text = "Format";
if(text.indexOf("Format") == 0) {
    alert(text + " = Format");
} else {
    alert(text + " != Format");
}

なぜそれが最善の方法ですか?
TylerH 2017年

1
indexOfメソッドは、startsWithの代わりではなく、指定された文字列のどこかに一致する場合に値を返します。indexOfの使用はお勧めしません。
RajKumarサマラ2017

12
indexOf戻り値を行いますが、@Jonaは、戻り値がゼロであることを確認した(つまり、文字列が先頭である)、それは意味あるのために良いの交換startsWith
SharpC 2018年

これは、ポリフィルを追加したり、ライブラリを追加したりする必要がないポリフィルと同じ機能です。これは優れたソリューションです-おそらく唯一の欠点はコードの読みやすさです。関数の名前がstartsWithであると意図がより明確になります。
John T

13

この場合は角度2+アプリケーションで起こっている、ことができますだけのコメントを外し内の文字列polyfills polyfills.ts

import 'core-js/es6/string';

Okaのポリフィル修正を追加しましたが、Angular 5アプリケーションでは機能しませんでしたが、import 'core-js/es6/string';修正しました。どうもありがとう!
18年

5

startsWith関数を次のものに置き換えます。

yourString.indexOf(searchString, position) // where position can be set to 0

これはIEを含むすべてのブラウザをサポートします

最初から0番目の位置を意味する文字列マッチングでは、位置を0に設定できます。


プロトタイプを書き直したり、ポリフィルを使用したりする必要がない便利なソリューション。さらに、ブラウザ間で幅広く互換性があります。+1
セルジオA.

2

他の人が言ったように、startsWithとendWithWithはES6の一部であり、IE11では使用できません。当社はIE11のポリフィルソリューションとして常にlodashライブラリを使用しています。https://lodash.com/docs/4.17.4

_.startsWith([string=''], [target], [position=0])

0

Okaの投稿はうまく機能していますが、少し時代遅れかもしれません。lodashが1つの単一の機能でそれに取り組むことができることを理解しました。lodashがインストールされている場合は、数行を節約できます。

ちょうど試して:

import { startsWith } from lodash;

。。。

    if (startsWith(yourVariable, 'REP')) {
         return yourVariable;        
    return yourVariable;
       }      
     }

0

私も最近問題に直面しました。のstartwithに似ている^を使用して解決しました jquery。いう、

var str = array[a].id;
if (str.startsWith('REP')) {..........}

私たちは使うことができます

if($("[id^=str]").length){..........}

ここで、strは要素のidです。


0

angular2 +プロジェクトでの作業中に問題が発生した場合は、この方法に従ってください

このエラーが発生したとき、私は解決策を探していました、そしてそれは私をここに連れて行きました。しかし、この質問は具体的なようですが、エラーはそうではなく、一般的なエラーです。これは、Internet Explorerを扱う角度のある開発者にとって一般的なエラーです。

私はangular 2+での作業中に同じ問題を抱えていましたが、いくつかの簡単な手順で解決しました。

Angularの最新バージョンでは、polyfills.tsにコメント付きのコードがあり 、Internet ExplorerバージョンIE09、IE10、IE11でスムーズに実行するために必要なすべてのポリフィルが表示されます

/** IE9, IE10 and IE11 requires all of the following polyfills. **/
//import 'core-js/es6/symbol';
//import 'core-js/es6/object';
//import 'core-js/es6/function';
//import 'core-js/es6/parse-int';
//import 'core-js/es6/parse-float';
//import 'core-js/es6/number';
//import 'core-js/es6/math';
//import 'core-js/es6/string';
//import 'core-js/es6/date';
//import 'core-js/es6/array';
//import 'core-js/es6/regexp';
//import 'core-js/es6/map';
//import 'core-js/es6/weak-map';
//import 'core-js/es6/set';

コードのコメントを外すと、IEブラウザーで完全に機能します

/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';

しかし、IEブラウザーでは他のブラウザーと比較してパフォーマンスが低下する可能性があります。

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.