2012-04-19 126 views
3

所以在我的javascript我有以下代碼:爲什麼`mystring [0]`在IE中不返回任何東西?

var wholeHash = window.location.hash.substring(1); 
    var data = new Object(); 

    // Remove the bang or slash if one appears at the beginning 
    if (wholeHash[0] == '!') { wholeHash = wholeHash.substring(1); } 
    if (wholeHash[0] == '/') { wholeHash = wholeHash.substring(1); } 

當這個快要用完,wholeHash"/search/&&stype=quick"值。但是,wholeHash[0]不會返回任何內容,這會導致wholeHash[0] == '!'爲假。這只是在IE中的情況。

這是爲什麼?我知道我可以改爲使用startswith,但我一般對IE瀏覽器在其他瀏覽器無法獲取字符串的單個字符時感興趣。

回答

6

因爲索引到具有數組樣式索引的字符串是新的,並且舊版本的IE缺少這個。相反,如果您需要在8之前支持IE,則需要使用mystring.charAt(0)

+0

請原諒我,但IE ***已***實施它。只是可能不是你仍在使用的任何原始版本的IE。 – 2012-04-19 19:49:41

+0

啊IE9有這個嗎?涼。 – 2012-04-19 19:50:10

+0

我使用IE9所以不,它沒有這個 – KallDrexx 2012-04-19 19:50:54

1

從字符串中獲取字符的「正確」方式是mystring.charAt(x)

但是,您可以使用mystring.split("")將字符串分解爲數組。

由你決定。

2

前段時間我有類似的問題。在我的情況下,它必須處理在Intranet頁面上自動打開的兼容性視圖。檢查this question