.includes()无法在Internet Explorer中使用

Car*_*sss 88 javascript

此代码在Internet Explorer中不起作用.还有其他选择

"abcde".includes("cd")
Run Code Online (Sandbox Code Playgroud)

Phi*_*lip 105

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
Run Code Online (Sandbox Code Playgroud)

MDN有一个includes使用的polyfill indexOf:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Polyfill

编辑:Opera支持includes版本28开始.

  • 如果我们需要一个`Boolean`,我们可以`(myString.indexOf('string')> -1)//得到一个布尔值true或false (6认同)

小智 27

或者只是把它放在一个Javascript文件中,祝你有个美好的一天:)

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

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

  return returnValue;
}
Run Code Online (Sandbox Code Playgroud)

  • 更短的版本:`return this.indexOf(str)!== -1;` (10认同)
  • 对于数组: Array.prototype.includes = function (elt) { return this.indexOf(elt) !== -1; } (2认同)

dee*_*ABC 8

大多数浏览器都不支持includes().您可以选择使用

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

或使用

-指数()

var str = "abcde";
var n = str.indexOf("cd");
Run Code Online (Sandbox Code Playgroud)

这给你n = 2

这得到了广泛的支持.


Joe*_*Joe 8

问题:

尝试从 Internet Explorer运行以下(无解决方案)并查看结果。

console.log("abcde".includes("cd"));
Run Code Online (Sandbox Code Playgroud)

解决方案:

现在运行下面的解决方案并检查结果

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"));
Run Code Online (Sandbox Code Playgroud)