[javascript] .includes ()가 Internet Explorer에서 작동하지 않음

이 코드는 Internet Explorer에서 작동하지 않습니다. 대안이 있습니까?

"abcde".includes("cd")



답변

String.prototype.includes 작성시 Internet Explorer (또는 Opera)에서 지원되지 않습니다.

대신 String.prototype.indexOf. #indexOf문자열에 있으면 하위 문자열의 첫 번째 문자의 인덱스를 반환하고 그렇지 않으면 반환합니다.-1 . (배열과 매우 유사 함)

var myString = 'this is my string';
myString.indexOf('string');
// -> 11

myString.indexOf('hello');
// -> -1

MDN에는 다음을 includes사용 하기위한 polyfill이 있습니다 indexOf. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Polyfill

편집 : 오페라 지원 includes 현재의 버전 (28) .

편집 2 : Edge의 현재 버전은 방법을 지원합니다. (2019 년 기준)


답변

아니면 그냥 자바 스크립트 파일에 넣고 좋은 하루 보내세요 🙂

String.prototype.includes = function (str) {
  var returnValue = false;

  if (this.indexOf(str) !== -1) {
    returnValue = true;
  }

  return returnValue;
}


답변

includes ()는 대부분의 브라우저에서 지원되지 않습니다. 귀하의 옵션은

-polyfill from MDN
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes

또는 사용

-indexof ()

var str = "abcde";
var n = str.indexOf("cd");

n = 2를줍니다.

이것은 널리 지원됩니다.


답변

문제:

Internet Explorer에서 아래 (솔루션없이) 실행 하고 결과를 확인하십시오.

console.log("abcde".includes("cd"));

해결책:

이제 솔루션 아래에서 실행하고 결과를 확인하십시오.

if (!String.prototype.includes) {//To check browser supports or not
  String.prototype.includes = function (str) {//If not supported, then define the method
    return this.indexOf(str) !== -1;
  }
}
console.log("abcde".includes("cd"));


답변

이것은 더 좋고 더 짧을 수 있습니다.

function stringIncludes(a, b) {
    return a.indexOf(b) >= 0;
}


답변

Angular 5에서 작업 할 때도 같은 문제가있었습니다. 직접 polyfill을 작성하지 않고 직접 작동하게하려면 polyfills.ts 파일에 다음 줄을 추가하면됩니다.

import "core-js/es7/array"

또한 tsconfig.jsonlib 섹션이 관련 될 수 있습니다.

"lib": [
  "es2017",
  "dom"
],


답변

반응 :

import 'react-app-polyfill/ie11';
import 'core-js/es5';
import 'core-js/es6';
import 'core-js/es7';

에 대한 문제 해결-includes (), find () 등 ..