$.parseJSON - 未捕获的语法错误 - 如何检查未定义

$.parseJSON - uncaught SyntaxError - how to check for undefined

本文关键字:何检查 未定义 检查 语法 parseJSON 错误      更新时间:2023-09-26

我有以下jQuery函数,当cookie $.cookie('chk_ar')未定义时,它会抛出Uncaught SyntaxError: Unexpected token u

function checkBgNoise() {
// check background noise option state,
// if true, click 'on' to activate
// then add classes and check checkboxes
if( $.cookie('bg-noise-state') === 'true' ) {
  $('#bg-noise-on').trigger('click');
  // check for bg-noise array cookie
  var chk_ar = $.cookie('chk_ar');
  // convert string to object
  chk_ar = $.parseJSON(chk_ar);
  // loop through and apply checks to matching sets
  $.each(chk_ar, function(index, value) {
    // add bg-noise class for activated areas
    $('.' + value).addClass('bg-noise');
    // check those areas
    $('input').filter('[data-at="'+value+'"]').prop('checked', true);
  });
} else if ( $.cookie('bg-noise-state') === 'false' ) {
  // remove classes when selecting 'off'
  var chk_ar = $.cookie('chk_ar');
  chk_ar = $.parseJSON(chk_ar);
  $.each(chk_ar, function(index, value) {
    // remove bg-noise added on toggling off noise
    $('.' + value).removeClass('bg-noise');
    // uncheck the boxes
    $('input').filter('[data-at="'+value+'"]').prop('checked', false);
  });      
};
}; // end function checkBgNoise

我仍在学习javascript绳索,所以我的方法完全有可能存在一些相当明显的错误。代码通常正常运行,但如果可能的话,我想摆脱错误。

在Stack Exchange和Google上搜索错误代码表明问题出在对$.parseJSON(chk_ar)的调用中,这有时是未定义的。关于如何解决这个问题的任何想法?一个简单的if陈述?

我做了一些轻微的修改,所以你在函数的顶部得到chk_ar,然后在未定义的情况下退出。 由于两个州都需要它,因此在顶部获取并检查是有意义的......

function checkBgNoise() {
    // get this here since both states need the value - exit if it's undefined
    var chk_ar = $.cookie('chk_ar');
    if (chk_ar == undefined) return;
    // check background noise option state,
    // if true, click 'on' to activate
    // then add classes and check checkboxes
    if( $.cookie('bg-noise-state') === 'true' ) {
        $('#bg-noise-on').trigger('click');
        // convert string to object
        chk_ar = $.parseJSON(chk_ar);
        // loop through and apply checks to matching sets
        $.each(chk_ar, function(index, value) {
            // add bg-noise class for activated areas
            $('.' + value).addClass('bg-noise');
            // check those areas
            $('input').filter('[data-at="'+value+'"]').prop('checked', true);
        });
    }
    else if ( $.cookie('bg-noise-state') === 'false' ) {
        // remove classes when selecting 'off'
        chk_ar = $.parseJSON(chk_ar);
        $.each(chk_ar, function(index, value) {
            // remove bg-noise added on toggling off noise
            $('.' + value).removeClass('bg-noise');
            // uncheck the boxes
            $('input').filter('[data-at="'+value+'"]').prop('checked', false);
        });      
    };
} // end function checkBgNoise