Answers:
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
使用indexOf
:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Polyfill
编辑:Opera includes
从28版本开始支持。
编辑2:当前版本的Edge支持该方法。(截至2019年)
Boolean
,我们可以(myString.indexOf('string') > -1) // to get a boolean true or false
或者只是将其放入Javascript文件中,祝您有美好的一天:)
String.prototype.includes = function (str) {
var returnValue = false;
if (this.indexOf(str) !== -1) {
returnValue = true;
}
return returnValue;
}
for...in
,String.prototype.includes
如果这样定义字符串,则会对其进行迭代。
return this.indexOf(str) !== -1;
大多数浏览器不支持include()。您可以选择使用
来自MDN的-polyfill https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes
或使用
-指数()
var str = "abcde";
var n = str.indexOf("cd");
给你n = 2
这得到了广泛支持。
for...in
!迭代字符串。,String.prototype.includes
如果您这样定义,它将进行迭代。
问题:
尝试从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.json
lib节可能是相关的:
"lib": [
"es2017",
"dom"
],
如果要继续使用Array.prototype.include()
JavaScript,可以使用以下脚本:
github-script-ie-include
如果检测到IE,它将自动将include()转换为match()函数。
其他选项是始终使用string.match(Regex(expression))
这个对我有用:
function stringIncludes(a, b) {
return a.indexOf(b) !== -1;
}
你也可以用!! 和〜运算子
var myString = 'this is my string';
!!~myString.indexOf('string');
// -> true
!!~myString.indexOf('hello');
// -> false
这是两个运算符(!!和〜)的解释
https://www.joezimjs.com/javascript/great-mystery-of-the-tilde/