Javascript 如何解决此“未捕获的类型错误:无法将未定义或空值转换为对象”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39199508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:20:03  来源:igfitidea点击:

How to resolve this " Uncaught TypeError: Cannot convert undefined or null to object "

javascriptjqueryruby-on-railsarrayshash

提问by Pooja Mokariya

My function is :

我的功能是:

function collect_que_ids(e) {
  var val = e.val();
  var data_lo = e.attr('data-lo');
  new_hash = {};
  new_hash[val] = data_lo;
  if(e.is(':checked')){
    if(checked_box_hash.includes(new_hash)){
      checked_box_hash;
    }else{
      checked_box_hash.push(new_hash);
    }
  }
  else{
    new_hash_key = Object.keys(new_hash)[0]
    new_hash_value = new_hash[new_hash_key]
    $.each(checked_box_hash, function(key, value){
      if (typeof Object.keys(value) !== 'nil') {
        current_key = Object.keys(value)
        if (current_key[0] == new_hash_key && value[current_key[0]] == new_hash_value) {
          checked_box_hash.splice(key, 1)
        }
      }
    })
  }
};

I am getting error on this line.

我在这条线上遇到错误。

if (typeof Object.keys(value) !== 'nil') {

Need to resolve it. please help to do.

需要解决它。请帮忙做。

回答by Amar Singh

Object.keys(value)returns an arrayand to check if it is undefined or empty do this

Object.keys(value)返回一个数组并检查它是否未定义或为空,请执行此操作

 if (typeof Object.keys(value) !== 'undefined' && Object.keys(value).length > 0) {
        // You have an array 
    }

回答by Rock Lee

If you are using React classes that extend PureComponent, then make sure you put your state in the class field, state = {...}, not the State type definition, type State = {...}, or else it will be an error because it actually was null.

如果您使用的是扩展的 React 类PureComponent,那么请确保将您的状态放在类字段中state = {...},而不是 State 类型定义中,type State = {...}否则它将是一个错误,因为它实际上是 null。