2017-06-01 801 views
0

我正在研究一個函數,該函數通過頁面上的表值列表查看,如果列標題包含output的任何部分,它將相應地轉換該值。Javascript .includes()在IE中不起作用

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()必須是並非所有瀏覽器都支持的東西。

有什麼我可以用來代替這將允許跨瀏覽器的支持?

+0

是不是那裏的MDN文檔中填充工具? – Barmar

+0

[鏈接到polyfill](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Polyfill) – Barmar

回答

3

取代:

if(field.toLowerCase().includes(key)) { 

到:

if(field.toLowerCase().indexOf(key) > -1) { 
1

供您參考,Mozilla Developer Network顯示了哪些瀏覽器支持String.prototype.includes

IE沒有任何支持。話雖如此,你可以隨時填充它,或者像別人指定並使用String.prototype.indexOf一樣。

填充工具的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; 
    } 
    }; 
}