.includes()在Internet Explorer中无法正常工作

125

这段代码在Internet Explorer中无法工作。有任何替代方案吗?

"abcde".includes("cd")

35
两年后,IE仍然不支持它。 - nu everest
7
等待IE变得更好就像……等待IE变得更好。 - Rob_M
2
@nueverest 你是指三年对吧? :D - Josh
4
有人能帮大家一个忙,把IE的仓库删掉吗?就此结束吧。 - zero_cool
1
又是一年。 - Lakshay Sharma
显示剩余6条评论
11个回答

152

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提供了一个使用indexOf的polyfill来实现includes的方法:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Polyfill

编辑:自版本28起,Opera支持includes方法。

编辑2:截至2019年,当前版本的Edge已经支持这种方法。


include()是IE不支持的唯一函数吗?还是有其他TypeScript或JavaScript函数在IE中不被支持? - Abdullah Feroz
10
若我们需要一个布尔值,我们可以使用(myString.indexOf('string') > -1)来获得真或假的布尔值。 - Aakash

39

或者将此放在JavaScript文件中,祝您拥有愉快的一天 :)

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

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

  return returnValue;
}

如果您使用此 polyfill,请勿使用 for...in 迭代字符串,因为它将迭代定义为 String.prototype.includes 的内容。 - Patrick Roberts
12
短版本:return this.indexOf(str) !== -1; - Andrew
2
对于数组:Array.prototype.includes = function (elt) { return this.indexOf(elt) !== -1; } - LePatay

11

如果您使用来自MDN的polyfill,请勿使用for...in迭代字符串!如果您这样定义,它将遍历String.prototype.includes - Patrick Roberts

9

问题:

Try running below(without solution) from Internet Explorer and see the result.

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

解决方案:

Now run below solution and check the result

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"));


4
这个可能更好,而且更简短:
function stringIncludes(a, b) {
    return a.indexOf(b) >= 0;
}

IE不支持indexOf函数。 - Some_Dude
1
它在IE11中运行得非常完美。也许在IE10中不行,但现在很少有人使用那个版本了。 - Andrew

3

我在使用Angular 5时也遇到了同样的问题。为了让它能直接工作,而不需要自己编写填充代码,只需将以下行添加到polyfills.ts文件中即可:

import "core-js/es7/array"

此外,tsconfig.json 的 lib 部分可能会相关:
"lib": [
  "es2017",
  "dom"
],

你,我的朋友,是一个完全的救星! - CodeMan03

3

对于React:

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

解决 - includes(),find()等的问题。

1
如果你想继续在JavaScript中使用Array.prototype.include(),你可以使用此脚本:github-script-ie-include。它会在检测到IE时自动将include()转换为match()函数。
另一个选择是始终使用string.match(Regex(expression))

1

它对我有效:

function stringIncludes(a, b) {
      return a.indexOf(b) !== -1;
}

0

这是因为IE不支持includes,所以需要创建一个点函数,并且在ES5中使用它,就像下面的ES6 includes()一样:

String.prototype.includes = function (str) {
 return this.indexOf(str) !== -1;
}

以下是字符串。
var myString = 'this is my string';

检查匹配如下:

console.log(myString.includes('string')); // true
console.log(myString.includes('street')); //false

现在你可以使用相同的indexOf方式来添加ES5中的includes


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接