【问题标题】:Function.keys to check if a variable data exists [duplicate]Function.keys 检查变量数据是否存在[重复]
【发布时间】:2020-04-30 08:10:00
【问题描述】:

我正在使用 JavaScript 的 Object 类来检查变量是否存在,然后再从 JSON 响应中使用它。
当我尝试调用该行代码时,出现此错误

无法将 undefined 或 null 转换为对象
在 Function.keys ()
在成功回调

这是我的尝试:

if (Object.keys(response.data.data.user_fk)) {
  $rootScope.username = response.data.data.user_fk.name;
}

请问我怎样才能得到正确的支票?

【问题讨论】:

  • 请问response.data.data.user_fk的值是多少。
  • 这能回答你的问题吗? How to check a not-defined variable in JavaScript
  • 如果您要检查user_fk 是否是response.data.data 的属性,那么Object.keys() 没有用处。您可以改为测试"user_fk" in response.data.data
  • 目标是在response.data.data中测试user_fk

标签: javascript angularjs


【解决方案1】:

如果您只想检查response.data.data.user_fk 是否存在,请使用:

if (response.data.data.user_fk) {
    $rootScope.username=response.data.data.user_fk.name;
}

请注意,如果 user_fk 为 false 或 0(在布尔函数中调用时所有结果为 false),则不会触发 if 中的代码。

Boolean(0) //false
Boolean(false) //false
Boolean([]) //true
Boolean({}) //true
Boolean(true) //true

在这种情况下,只需将其与 undefined 或 null 进行比较:

if (value !== undefined && value !== null) {
    //Execute code that uses value
}

【讨论】:

    【解决方案2】:
    ...
    if(Object.keys(response.data.data.user_fk)){
    ...
    

    对于给定的问题,我只能这么说

    responseresponse.dataresponse.data.dataresponse.data.data.user_fkundefinednull

    因此,您可能会在某处收到 null 或在某些操作期间丢失数据。 但在提供的问题中,没有足够的数据来回答更具体的问题

    【讨论】:

      猜你喜欢
      • 2014-01-20
      • 2018-08-13
      • 2016-03-23
      • 2017-12-15
      • 1970-01-01
      • 2011-03-30
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多