gpt4 book ai didi

javascript - 为什么在比较时与 ""不同

转载 作者:行者123 更新时间:2023-12-03 08:27:41 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





JavaScript regex whitespace characters

(5 个回答)


2年前关闭。




你能解释一下为什么我会得到 false比较 text === ' '在这种情况下?

var div = document.getElementById('d');

div.innerHTML = ' ';

// ' '
var text = div.innerText;

console.log(/\s/.test(' ')); // true
console.log(/\s/.test(text)); // true
console.log(text === ' '); // false
#d {
border: 1px solid;
position: absolute;
}
<div id="d"></div>


这似乎不符合逻辑: \s是 A, ' '是 B, text是 C。
A  = B
A = C
B != C ???

最佳答案

空间" "non-breaking space是两个不同的字符。不间断空格的代码单元为 160,而空格的代码单元为 32。
从这个观察出发,当在两个非数字类型之间使用严格相等时,规范使用以下逻辑:
7.2.13 SameValueNonNumeric ( x, y )

The internal comparison abstract operation SameValueNonNumeric(x, y),where neither x nor y are numeric type values, produces true or false.Such a comparison is performed as follows:

  • Assert: Type(x) is not Number or BigInt. Assert: Type(x) is the sameas Type(y).

  • If Type(x) is Undefined, return true. If Type(x) is Null,return true.

  • If Type(x) is String, then

  • If x and y are exactly thesame sequence of code units (same length and same code units atcorresponding indices), return true; otherwise, return false....


上面的最后一条语句不正确,因为两者具有不同的代码单元值(如上所示),因此我们得到 false当您尝试比较两者时。这不应该太令人惊讶,因为我们正在比较两个不同的字符串(如它们的代码单元值所示)。
当您使用 \s但是,在正则表达式中,您指的是特殊的空白字符:

Matches a single white space character, including space, tab, form feed, line feed, and other Unicode spaces. Equivalent to

[ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]

- MDN


上面的字符集包括空格字符(在字符集的开头看到)和不间断空格(Unicode 编码为 U+00A0),因此您使用正则表达式的两个测试都将返回 true。

关于javascript - 为什么在比较时与 ""不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59486536/

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