这段代码在Internet Explorer中无法工作。有任何替代方案吗?
"abcde".includes("cd")
这段代码在Internet Explorer中无法工作。有任何替代方案吗?
"abcde".includes("cd")
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已经支持这种方法。
(myString.indexOf('string') > -1)
来获得真或假的布尔值。 - Aakash或者将此放在JavaScript文件中,祝您拥有愉快的一天 :)
String.prototype.includes = function (str) {
var returnValue = false;
if (this.indexOf(str) !== -1) {
returnValue = true;
}
return returnValue;
}
for...in
迭代字符串,因为它将迭代定义为 String.prototype.includes
的内容。 - Patrick Robertsreturn this.indexOf(str) !== -1;
- Andrewincludes()在大多数浏览器中不被支持。你的选择是使用MDN上的polyfill,具体请参考https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes,或者使用indexOf()。
var str = "abcde";
var n = str.indexOf("cd");
这将给你n=2。
这得到广泛支持。
for...in
迭代字符串!如果您这样定义,它将遍历String.prototype.includes
。 - Patrick Roberts问题:
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"));
function stringIncludes(a, b) {
return a.indexOf(b) >= 0;
}
我在使用Angular 5时也遇到了同样的问题。为了让它能直接工作,而不需要自己编写填充代码,只需将以下行添加到polyfills.ts文件中即可:
import "core-js/es7/array"
tsconfig.json
的 lib 部分可能会相关:"lib": [
"es2017",
"dom"
],
对于React:
import 'react-app-polyfill/ie11';
import 'core-js/es5';
import 'core-js/es6';
import 'core-js/es7';
Array.prototype.include()
,你可以使用此脚本:github-script-ie-include。它会在检测到IE时自动将include()转换为match()函数。string.match(Regex(expression))
。它对我有效:
function stringIncludes(a, b) {
return a.indexOf(b) !== -1;
}
这是因为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