[英]Javascript .includes() not working in IE
我正在研究一個查看頁面上的表值列表的函數,如果列標題包含output
任何部分,它將相應地轉換該值。
function createLink(field, val) {
var output = {
'ntid': 'https://internal/profile/' + val,
'email': 'mailTo:' + val
};
var i, key, keys = Object.keys(output);
for ( i = 0; i < keys.length; ++i ) {
key = keys[i];
if ((field.toLowerCase()).includes(key)) {
return '<a href="'+output[key]+'" target="_blank">'+val+'</a>';
}
}
return val;
}
我遇到的問題是IE在.includes()
行上拋出一個錯誤,指出“對象不支持屬性或方法'包含'”。
我有點麻煩讓它按原樣工作,但沒有意識到includes()
必須是並非所有瀏覽器都支持的東西。
是否有其他我可以使用的東西來支持跨瀏覽器支持?
includes()
是ES6
規范的一部分 ,因此IE不支持它。 你可以使用的是indexOf(element) !== -1
更換:
if(field.toLowerCase().includes(key)) {
至:
if(field.toLowerCase().indexOf(key) > -1) {
供您參考, Mozilla Developer Network顯示哪些瀏覽器支持String.prototype.includes
。
IE沒有任何支持。 話雖如此,您可以隨時對其進行填充,或者像其他人指定的那樣進行填充,並使用String.prototype.indexOf
。
Polyfill src: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Polyfill
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
'use strict';
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > this.length) {
return false;
} else {
return this.indexOf(search, start) !== -1;
}
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.