此代码在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开始.
小智 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)
大多数浏览器都不支持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
这得到了广泛的支持.
问题:
尝试从 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)
归档时间: |
|
查看次数: |
100221 次 |
最近记录: |