如果子字符串为空,如何跳过并避免控制台出错?

rob*_*b.m 0 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);
Run Code Online (Sandbox Code Playgroud)

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

Uncaught TypeError: Cannot read property 'substring' of undefined
Run Code Online (Sandbox Code Playgroud)

另一个问题中的建议答案

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

但我仍然得到同样的错误

geo*_*org 5

您可以防御并在使用之前检查密钥是否存在:

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

或者只是用一个空字符串来保护它:

var ag = (partDic["comboFilters[Agencies]"] || "").substring(1);
Run Code Online (Sandbox Code Playgroud)