如果没有子字符串以避免控制台中的错误,如何跳过?

我正在设置子串

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; }); setTimeout( function() { var ag = partDic["comboFilters[Agencies]"].substring(1); $('.Agency .dropdown-toggle').html(ag).append(' '); var cl = partDic["comboFilters[Clients]"].substring(1); $('.Client .dropdown-toggle').html(cl).append(' '); var yr = partDic["comboFilters[Years]"].substring(1).slice(1); $('.Year .dropdown-toggle').html(yr).append(' '); }, 1000); 

但如果没有子串,我得到:

 Uncaught TypeError: Cannot read property 'substring' of undefined 

我猜我需要一个简单的if / else但我不知道如何在这种情况下

使用

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

使用条件如:

 If(partDic["comboFilters[Agencies]"].length>0) { ----your code--- } else{} 

多亏了这个答案 ,我得到了这个解决方案:

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