最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript identity operator on strings - Stack Overflow

programmeradmin4浏览0评论

I'm trying to write a prototype for determining if a string is empty. It's really just playing with JS and prototype, nothing important. Here's my code:

String.prototype.IsEmpty = function() {
  return (this === "");
}

Notice I used the === identity parison instead of == equality. When I run the function with the above definition:

"".IsEmpty(); // false

If I chagne the definition to use == as:

String.prototype.IsEmpty = function() {
  return (this == "");
}

The new def'n will do:

"".IsEmpty(); // true

I don't understand why === doesn't work since "" is identical to ""

I'm trying to write a prototype for determining if a string is empty. It's really just playing with JS and prototype, nothing important. Here's my code:

String.prototype.IsEmpty = function() {
  return (this === "");
}

Notice I used the === identity parison instead of == equality. When I run the function with the above definition:

"".IsEmpty(); // false

If I chagne the definition to use == as:

String.prototype.IsEmpty = function() {
  return (this == "");
}

The new def'n will do:

"".IsEmpty(); // true

I don't understand why === doesn't work since "" is identical to ""

Share Improve this question asked Oct 21, 2009 at 21:12 Mark UrsinoMark Ursino 31.4k12 gold badges53 silver badges83 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 10

It's because "" is a string primitive, but when you call .IsEmpty() it's implicitly converted to a String object.

You'd need to call .toString() on it:

String.prototype.IsEmpty = function() {
  return (this.toString() === "");
}

Interestingly this is browser-specific - typeof this is string in Chrome.

As @pst points out, if you were to convert the other way and pare this === new String(""); it still wouldn't work, as they're different instances.

=== is identity (same object; x is x**). == is equality (same value; x looks like y).

Lets play some (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

So, what just happened?

The difference between a String object and string. Of course, the equality pare (or .length) should be used.

The proof in the pudding, section 11.9.6 discusses the === operator algorithm

发布评论

评论列表(0)

  1. 暂无评论