gpt4 book ai didi

javascript - 有人可以用 javascript 解释这种行为吗?

转载 作者:数据小太阳 更新时间:2023-10-29 04:06:36 27 4
gpt4 key购买 nike

在 Firefox 中测试:

a = [] + 0;
b = 0;

alert(a); // 0
alert(b); // 0

alert(!a); // false
alert(!b); // true

最佳答案

+ concatenation operator导致 toString 评估 0

因此 a 的值为 "0",而 b 的值为 0

来自 ECMAScript 11.6.1 加法运算符 (+)

The addition operator either performs string concatenation or numeric addition. The production AdditiveExpression : AdditiveExpression + MultiplicativeExpression is evaluated as follows:

  1. Let lref be the result of evaluating AdditiveExpression.

  2. Let lval be GetValue(lref).

  3. Let rref be the result of evaluating MultiplicativeExpression.

  4. Let rval be GetValue(rref).

  5. Let lprim be ToPrimitive(lval).

  6. Let rprim be ToPrimitive(rval).

  7. If Type(lprim) is String or Type(rprim) is String, then

    a. Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)

  8. Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim). See the Note below 11.6.3.

NOTE 1 No hint is provided in the calls to ToPrimitive in steps 5 and 6. All native ECMAScript objects except Date objects handle the absence of a hint as if the hint Number were given; Date objects handle the absence of a hint as if the hint String were given. Host objects may handle the absence of a hint in some other manner.

NOTE 2 Step 7 differs from step 3 of the comparison algorithm for the relational operators (11.8.5), by using the logical-or operation instead of the logical-and operation.

关于javascript - 有人可以用 javascript 解释这种行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4772027/

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