字符串上的JavaScript身份运算符

Mar*_*ino 10 javascript

我正在尝试编写一个原型来确定字符串是否为空.它真的只是玩JS和原型,没什么重要的.这是我的代码:

String.prototype.IsEmpty = function() {
  return (this === "");
}
Run Code Online (Sandbox Code Playgroud)

注意我使用了===身份比较而不是==相等.当我运行具有上述定义的函数时:

"".IsEmpty(); // false
Run Code Online (Sandbox Code Playgroud)

如果我将定义==用作:

String.prototype.IsEmpty = function() {
  return (this == "");
}
Run Code Online (Sandbox Code Playgroud)

新def'n会做:

"".IsEmpty(); // true
Run Code Online (Sandbox Code Playgroud)

我不明白为什么===不起作用,因为""是相同的""

Gre*_*reg 10

这是因为""是一个字符串原语,但是当你调用.IsEmpty()它时会隐式转换为一个String对象.

你需要在它上面调用.toString():

String.prototype.IsEmpty = function() {
  return (this.toString() === "");
}
Run Code Online (Sandbox Code Playgroud)

有趣的是,这是特定浏览器- typeof thisstring在Chrome.

正如@pst指出的那样,如果你要转换另一种方式并进行比较this === new String("");它仍然不起作用,因为它们是不同的实例.


小智 9

===是身份(同一个对象; x是x**).==是相等(相同的值; x看起来像y).

让我们玩一些(Rhino/JS 1.8):

{} === {} // false
new String("") === new String("") // false
typeof new String("") // object

"" === "" // true
typeof "" // string
f = function () { return "f" };
"foo" === f() + "oo" // true

String.prototype.foo = function () { return this; };
typeof "hello".foo() // object -- uh, oh! it was lifted
Run Code Online (Sandbox Code Playgroud)

刚刚发生了什么?

String对象和字符串之间的区别.当然,应该使用相等比较(或.length).

布丁中证明,第11.9.6节讨论了===运算符算法