如果substring为null并且在控制台中避免错误,如何跳过?

时间:2015-01-16 10:20:13

标签: javascript jquery

抓住子串:

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):'';

但我仍然得到同样的错误

4 个答案:

答案 0 :(得分: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);

答案 1 :(得分:2)

也许尝试使用以下内容:

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

答案 2 :(得分:0)

您可以尝试检查它的类型:

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

请注意,您应为所有变量添加此检查:agclyr

答案 3 :(得分:0)

您可以在使用子字符串方法之前检查一个条件。

if((!hash) || (!hash.substring(1)){
return false;
}