简体   繁体   中英

Javascript strict equality strangeness

If I do:

!isNaN('2') && parseInt('2').toString() === '2'    // returns 'true'

I have the following JavaScript function:

String.prototype.isDigit = function() {
    return !isNaN(this) && parseInt(this).toString() === this ? true : false;
}

However:

'2'.isDigit()    // returns 'false'

Furthermore,

String.prototype.isDigit = function() {
    return this === '2' ? true : false;
}
'2'.isDigit()    // returns 'false'

What is the discrepancy here? Shouldn't this === '2' ?

Shouldn't this === '2' ?

No, actually. In this case, this is actually an instance of String , which is different from the string primitive '2' . this is essentially equal to new String('2') , and each instance of such an object is unique.

You could cast it to a string primitive though.

String.prototype.isDigit = function() {
    var that = '' + this;
    return !isNaN(that) && parseInt(that).toString() === that ? true : false;
}

'2'.isDigit();

In your .isDigit() method, this is a String object (not a string primitive) and === with an object is only true if the two operands are exactly the same object, not just two separate objects with the same value or not with one an object and another a primitive.

So, in your method:

String.prototype.isDigit = function() {
    console.log(typeof parseInt(this).toString());   // "string"
    console.log(typeof this);                        // "object"
    return !isNaN(this) && parseInt(this).toString() === this ? true : false;
}

And, === will never be true for two operands that are different types.


You can stay with your approach, but use .valueOf() to get the primitive because comparing two string primitives with === just compares their values:

String.prototype.isDigit = function() {
    return !isNaN(this) && parseInt(this).toString() === this.valueOf();
}

Try opening up the console and doing:

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

You'll see "this" is an object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM