0

{}置き換える必要があるパラメーターを呼び出す API があります。しかし、次のような問題があります... 以下で何が起こるか分かりますか?

const log = console.log

const a = {}

log('a is ', a)

// cannot compare with either == or ===
if (a == {}) {
  log('a is {}')
} else {
  log('a is NOT {}')
}

// a is truthy too
const b = (a || 'not a')

console.log('b is ', b)

それで、その両方が真実であり、比較に失敗したことを考えると、それを置き換える方法を考えていますか?

また、内部でどのようなオブジェクト比較が行われているのかを知りたいです。

私の理解は次のとおりでした:

  • ==値が等しいかどうかをテスト (比較)
  • ===参照によって等しいかどうかテストされます (メモリ内の同じオブジェクトへのポインター)。

しかし、オブジェクトの実際の比較を行う必要があると思いますか? 私はこれをユニットテストフレームワークで行うことに慣れてtoBe()toEqualますtoDeepEqual

そして、ワット!

4

4 に答える 4

0

Object always has a true boolean value (object exists? then true). Primitives like strings and numbers are compared by their value, while objects like arrays, dates, and plain objects are compared by their reference. That comparison by reference basically checks to see if the objects given refer to the same location in memory. You can check if objects are equals by JSON.stringify.

const a = {}

if (JSON.stringify(a) === JSON.stringify({})) {
  log('a is {}')
} else {
  log('a is NOT {}')
}

console.log(Boolean({}));   //Object exist?: True

const b = (a || 'not a')
console.log('b is ', b)

于 2020-07-23T03:39:29.557 に答える