如何清除此JavaScript null错误?

时间:2015-02-27 09:33:41

标签: javascript

我使用以下内容根据斜杠后的网址的最后一个字创建if语句:

  // Sticky

  var match = location.search.match(/(\w+)$/)[0];

  if (match === 'complete') {
    $('p:has(audio)').addClass('sticky-child');
    $('p:has(audio)').appendTo('.lesson_lang_switch');
  }

问题是,首页在URL的末尾没有任何单词(斜杠后):

  

www.example.com /

所以我收到了这个错误:

Uncaught TypeError: Cannot read property '0' of null 

我该怎么做才能显示错误?

5 个答案:

答案 0 :(得分:6)

您可以添加条件检查。即。

var match = (location.search.match(/(\w+)$/)) 
    ? location.search.match(/(\w+)$/)[0] 
    : "";

 if (match === 'complete') { // match will be "" if the above is false
    $('p:has(audio)').addClass('sticky-child');
    $('p:has(audio)').appendTo('.lesson_lang_switch');
 }

答案 1 :(得分:4)

您可以检查值是否为null

 // Sticky
 var loc = "www.example.com/";
 var match = loc.match(/(\w+)$/) === null ? "" : loc.match(/(\w+)$/)[0];

 if (match === 'complete') {
     $('p:has(audio)').addClass('sticky-child');
     $('p:has(audio)').appendTo('.lesson_lang_switch');
 }

fiddle

答案 2 :(得分:3)

您必须检查搜索是否确实存在。你可能想做这样的事情:

var match = location.search ? location.search.match(/(\w+)$/)[0] : undefined;

if (match === 'complete') {
    $('p:has(audio)').addClass('sticky-child');
    $('p:has(audio)').appendTo('.lesson_lang_switch');
}
如果location.search ?内有值,则

location.search将返回true,如果确实存在,那么正则表达式将完成。否则它将获得未定义的值。

您收到此错误的原因是location.search没有任何值。正则表达式返回null。因为您尝试从[0]阅读null,您将收到此错误。

答案 3 :(得分:2)

你可以检查是否有类似的东西:

var match = location.search.match(/(\w+)$/);
  if(match != null){
    match = match[0];
    if (match === 'complete') {
      $('p:has(audio)').addClass('sticky-child');
      $('p:has(audio)').appendTo('.lesson_lang_switch');
    }
  }

答案 4 :(得分:2)

string.match返回包含匹配结果的数组,如果没有匹配则返回 null 。有了这个说法,我建议您在尝试应用和索引之前检查location.search.match返回的内容。

示例:

var matches = location.search.match(/(\w+)$/);

if(matches){
    var match = matches[0];
    if (match === 'complete') {
        $('p:has(audio)').addClass('sticky-child');
        $('p:has(audio)').appendTo('.lesson_lang_switch');
    }
}

如果您想了解有关JavaScript的string.match方法的更多信息,请参阅here