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

WAT!

4

4 回答 4

1

如果您需要做的就是检测某物是否为空对象,那么这样的事情可能会起作用:

const a = {};
const b = { hello: 'world' };
const c = 'test';

function isEmptyObject(arg) {
  return typeof arg === 'object' && Object.keys(arg).length === 0;
}

console.log(`a is ${isEmptyObject(a)}`);
console.log(`b is ${isEmptyObject(b)}`);
console.log(`c is ${isEmptyObject(c)}`);

于 2020-07-23T03:39:11.910 回答
1

也许这会澄清一些事情:

let a = {}; // Object Literal
let b = {}; // Object Literal
let c = a;  

// both a and b above are separate objects

console.log(b == a)   // false
console.log(c == a)   // true
console.log({} == {}) // false, as both are different Objects

// if you want to test if two things are the same type you could do
console.log(({}).toString() == ({}).toString()) // true
console.log(a.toString() == b.toString()) // true

// the reason why those work is, because now we are comparing strings... not the objects
console.log(({}).toString()) // "[object Object]"

// to simply check that the Object is "true", you could.
console.log(!!{});

// Specifying your own false, if empty comparisons "as values"...

console.log(!!Object.keys({}).length) // false
// or, even
console.log( !("{}" == JSON.stringify({}) ) ) // false

如果感兴趣的对象有可能是函数或包含任何非 json 安全值,我会警告不要使用 JSON.stringify,因为在比较函数或误报的情况下会出现错误


JavaScript 平等

=== 是严格相等比较(“identity”

== 是抽象平等比较(“松散平等”)

“===”很简单,被比较的对象是同一个对象“实例”

“==”有点复杂,因为强制开始发挥作用,所以它更像是“它们可以一样吗”

查看这篇文章,了解正在发生的事情的机制......

松散等式与严格等式

松散等于是 == 运算符,严格等于是 === 运算符。这两个运算符都用于比较“平等”的两个值,但“松散”与“严格”表明两者之间的行为存在非常重要的差异,特别是它们如何决定“平等”。

关于这两个运算符的一个非常常见的误解是:“== 检查值是否相等,=== 检查值和类型是否相等。” 虽然这听起来不错且合理,但它是不准确的。无数备受推崇的 JavaScript 书籍和博客都明确表示过这一点,但不幸的是,它们都错了。

正确的描述是:“== 允许在相等比较中进行强制转换,而 === 不允许进行强制转换。

于 2020-07-23T03:45:19.433 回答
0

你可以试试这个

const a = {}

log=console.log
log('a is ', a)

// cannot compare with either == or ===
if (typeof a == "object"&& Object.keys(a).length==0) {// the && part to check if the object is empty
  log('a is {}')
} else {
  log('a is NOT {}')
}

于 2020-07-23T03:37:16.900 回答
0

对象总是有一个真正的布尔值(对象存在?然后是真的)。像字符串和数字这样的原语是通过它们的值来比较的,而像数组、日期和普通对象这样的对象是通过它们的引用来比较的。通过引用进行比较基本上检查给定的对象是否引用内存中的相同位置。您可以通过 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 回答