gpt4 book ai didi

javascript - JavaScript 中的空比较会强制执行什么操作?

转载 作者:行者123 更新时间:2023-11-30 08:27:14 24 4
gpt4 key购买 nike

如果我有这个 JavaScript

var someVar = someOtherVar == null;

someOtherVar 的哪些值会导致 someVar 为真?

注意:据我所读,如果 someOtherVarundefined,则 someVar 将为真。但是我正在更改我的很多代码以使用这种比较方式,并且我想确保没有其他内容会导致 truthy 语句(除了 null未定义)。

最佳答案

What values of someOtherVar will cause someVar to be true?

只有 nullundefined

The algorithm in the spec is relatively straight forward :

  1. If Type(x) is the same as Type(y), then Return the result of performing Strict Equality Comparison x === y.
  2. If x is null and y is undefined, return true.
  3. If x is undefined and y is null, return true.
  4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
  5. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
  6. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
  7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
  8. If Type(x) is either String, Number, or Symbol and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
  9. If Type(x) is Object and Type(y) is either String, Number, or Symbol, return the result of the comparison ToPrimitive(x) == y.
  10. Return false.

第 1 步处理 null == null 的情况。第 2 步和第 3 步处理情况 null == undefinedundefined == null。第 6 步和第 7 步处理另一个值为 bool 值的情况,因此您最终将一个数字与 null 进行比较。由于 null 不是对象、数字、字符串、 bool 值或符号,因此其他步骤均不适用,因此返回 false(第 10 步)。


What coerces from a null compare in JavaScript?

只有当另一个值是一个 bool 值时,它才会被强制转换为一个数字,所以你最终会比较0 == null1 == null,两者均为 false

在所有其他情况下,没有类型强制发生(没有任何内容被强制转换为 null 并且 null 没有被强制转换为任何其他数据类型)。

关于javascript - JavaScript 中的空比较会强制执行什么操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43597144/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com