。包括()不在 Internet Explorer 工作

这个代码在 Internet Explorer 不起作用,还有其他选择吗?

"abcde".includes("cd")
171245 次浏览

正如你所写的,Internet Explorer (或 Opera)不支持 String.prototype.includes

Instead you can use String.prototype.indexOf. #indexOf returns the index of the first character of the substring if it is in the string, otherwise it returns -1. (Much like the Array equivalent)

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


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

MDN has a polyfill for includes using indexOf: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Polyfill

EDIT: Opera supports includes as of 版本28.

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

Include ()不受大多数浏览器的支持

- 来自 MDN 的填料 Https://developer.mozilla.org/en/docs/web/javascript/reference/global_objects/string/includes

或使用

-indexof()

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

Which gives you n=2

这一点得到了广泛支持。

或者把它放到一个 Javascript 文件中,然后祝你有美好的一天:)

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


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


return returnValue;
}

If you want to keep using the Array.prototype.include() in javascript you can use this script: Github-script-ie-include That converts automatically the include() to the match() function if it detects IE.

另一种选择是始终使用 string.match(Regex(expression))

这个可能更好,也更短:

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

问题:

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

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

Solution:

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

您可以对! ! 和 ~ 操作符进行同样的操作

 var myString = 'this is my string';


!!~myString.indexOf('string');
// -> true


!!~myString.indexOf('hello');
// -> false

here's the explanation of the two operators (!! and ~ )

JavaScript 中的! (不是不)运算符是什么?

Https://www.joezimjs.com/javascript/great-mystery-of-the-tilde/

我在角度5工作时也遇到过同样的问题。为了让它直接工作而不需要自己编写一个 polyfill,只需要将以下代码行添加到 polyfils.ts 文件中:

import "core-js/es7/array"

此外,tsconfig.json lib 部分可能是相关的:

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

反应:

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

问题解决 for-include ()、 find ()等等。

It works for me:

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

这是因为即不支持包括所以 创建一个点函数并使用它,就像 es6在 es5中的 include ()一样,如下所示:

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

现在您可以使用相同的 索引包括的方式为 ES5添加这个