对象为null,而typeof为对象?

时间:2019-03-04 15:42:00

标签: javascript vue.js

我遇到了无法复制的问题。我个人没有得到这个错误,但是有些人根据bugsnag做到了。参见代码行6。

$queryWithParent = SaleService::query()
->distinct('properties.parent_id')
->whereNotNull('properties.parent_id')
->join('properties', 'sale_services.property_id', '=', 'properties.id')
->orderBy('parent_id')
->orderBy('sale_services.index_range', 'desc');

2 个答案:

答案 0 :(得分:1)

  let lang = this.$store.state.lang

  if(!lang){
    lang = 'nl'
  }
  if (name && typeof name === 'object') {
    if (typeof name[lang] === 'string' && name[lang]) { // <- null is not an object (evaluating 't[e]')
      return name[lang]
    }
    return name['nl'] ? name['nl'] : ''
  }
  return ''

答案 1 :(得分:1)

当其他人对您的问题发表评论时,typeof null在{strong> JavaScript 上给出了object

console.log(typeof null);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

下表总结了typeof的可能返回值(来自MDN):

Type                                                    | Result
Undefined                                               | "undefined"
Null                                                    | "object" (see below)
Boolean                                                 | "boolean"
Number                                                  | "number"
String                                                  | "string"
Symbol (new in ECMAScript 2015)                         | "symbol"
Host object (provided by the JS environment)            | Implementation-dependent
Function object (implements [[Call]] in ECMA-262 terms) | "function"
Any other object                                        | "object"

现在,查看您的代码,我相信它可以通过这种方式重新排列:

let lang = this.$store.state.lang

if (!lang)
    lang = 'nl'

if (name && name[lang] && typeof name[lang] === 'string')
    return name[lang];

return '';

请注意,由于您是在未定义nl的情况下定义默认语言的,因此无需进行下一个显式检查:

return name['nl'] ? name['nl'] : ''