2015-01-16 64 views
-1

抓住子:如果子字符串爲空並避免控制檯出錯,如何跳過?

var hash = document.location.hash; 

// create an object to act like a dictionary to store each value indexed by its key 
var partDic = {}; 

// remove the leading "#" and split into parts 
var parts = hash.substring(1).split('&'); 

// If you just want the first value, whatever it is, use this. 
// But be aware it's a URL so can be set to anything in any order, so this makes little sense 
// var string = parts[0].split('=')[1]; 

// build the dictionary from each part 
$.each(parts, function(i, v) { 
    // do the "=" split now 
    var arr = v.split("="); 

    // decode to turn "%5B" back into "[" etc 
    var key = decodeURIComponent(arr[0]); 
    var value = decodeURIComponent(arr[1]); 

    // store in our "dictionary" object 
    partDic[key] = value; 
}); 

// Set a delay to wait for content to fully load 
setTimeout(function() { 
    var ag = partDic["comboFilters[Agencies]"].substring(1); 
    $('.Agency .dropdown-toggle').html(ag).append(' <span class="caret"></span>'); 
    var cl = partDic["comboFilters[Clients]"].substring(1); 
    $('.Client .dropdown-toggle').html(cl).append(' <span class="caret"></span>'); 
    var yr = partDic["comboFilters[Years]"].substring(1).slice(1); 
    $('.Year .dropdown-toggle').html(yr).append(' <span class="caret"></span>'); 
}, 1000); 

但是,如果沒有一個子,我越來越:

Uncaught TypeError: Cannot read property 'substring' of undefined 

Suggested answer in another question

var cl = (partDic["comboFilters[Clients]"] && partDic["comboFilters[Clients]"].length>0)?partDic["comboFilters[Clients]"].substring(1):''; 

但我仍然得到同樣的錯誤

+0

見:http://stackoverflow.com/questions/25973300/can-i-use-the-in -key-to-test-a-property-in-an-tree-object – Hacketo

回答

3

你可以防守,並檢查一個關鍵前在使用它之前派:

if("comboFilters[Agencies]" in partDic) { 
     var ag = partDic["comboFilters[Agencies]"].substring(1); 
     $('.Agency .dropdown-toggle').html(ag).append(' <span class="caret"></span>'); 
    } 

或只是一個空字符串維護它:

var ag = (partDic["comboFilters[Agencies]"] || "").substring(1); 
+0

以上得到了上述答案。謝謝 –

+0

像第二個。 – CodeSmith

0

你可以嘗試檢查它的類型:

var cl = (typeof partDic["comboFilters[Clients]"] === 'string')?partDic["comboFilters[Clients]"].substring(1):''; 

注意,你應該添加此檢查所有的變量:agclyr

+0

這不會產生錯誤,但會改變文本爲空 –

+0

正確,這意味着'partDic [「comboFilters [Clients]」]'type不是'串'。 'substring'方法僅適用於字符串。 'console.log(partDic [「comboFilters [Clients]」])'說的是什麼? – antyrat

+0

如果檢查效果很好,那麼在 –

2

也許事情就像嘗試:

var parts = (hash && hash.substring(1).split('&')) || []; 
0

可以使用子方法之前檢查一個條件..

if((!hash) || (!hash.substring(1)){ 
return false; 
} 
相關問題