.includes()在Internet Explorer中不起作用


105

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

"abcde".includes("cd")

33
两年后,IE仍然不支持它。
珠穆朗玛峰

4
等待IE变得更好就像...等待IE变得更好。
Rob_M

1
@nueverest你的意思是三年吗?:D
乔什(Josh)

2
有人请大家帮忙,并删除IE的存储库。结束吧。
zero_cool

再过两年
-IE

Answers:


131

String.prototype.includes 如您所写,Internet Explorer(或Opera)不支持。

相反,您可以使用String.prototype.indexOf#indexOf返回子字符串的第一个字符的索引(如果它在字符串中),否则返回-1。(非常类似于Array的等效项)

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

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

MDN有一个填充工具includes使用indexOfhttps://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Polyfill

编辑:Opera includes28版本开始支持。

编辑2:当前版本的Edge支持该方法。(截至2019年)


是include()是IE不支持的唯一功能吗?还是IE不支持其他打字稿或JavaScript函数?
Abdullah Feroz

10
如果需要Boolean,我们可以(myString.indexOf('string') > -1) // to get a boolean true or false
Akash

32

或者只是将其放入Javascript文件中,祝您有美好的一天:)

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

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

  return returnValue;
}

如果您使用此polyfill,请不要使用来迭代您的字符串for...inString.prototype.includes如果这样定义字符串,则会对其进行迭代。
Patrick Roberts

10
较短的版本:return this.indexOf(str) !== -1;
Andrew

1
对于数组:Array.prototype.includes = function(elt){return this.indexOf(elt)!== -1; }
LePatay '19


6

问题:

尝试从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"));


4

这可能更好或更短:

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

IE不支持indexOf
Some_Dude

1
它在IE11中工作得很好。也许它不在IE10中,但如今几乎没有人在使用该版本。
安德鲁(Andrew)

3

在Angular 5中工作时,我遇到了同样的问题。为了使其直接工作而无需自己编写polyfill,只需将以下行添加到polyfills.ts文件中:

import "core-js/es7/array"

另外,tsconfig.jsonlib节可能是相关的:

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

你我的朋友是一个完整的救星!
CodeMan03 '19

2

对于反应:

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

问题解决-include(),find()等。


1

如果要继续使用Array.prototype.include()JavaScript,可以使用以下脚本: github-script-ie-include 如果检测到IE,它将自动将include()转换为match()函数。

其他选项是始终使用string.match(Regex(expression))



By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.