Casting to string in JavaScript

前端 未结 8 1697
轻奢々
轻奢々 2020-12-04 07:59

I found three ways to cast a variable to String in JavaScript.
I searched for those three options in the jQuery source code, and they are all in use

相关标签:
8条回答
  • 2020-12-04 08:48

    In addition to all the above, one should note that, for a defined value v:

    • String(v) calls v.toString()
    • '' + v calls v.valueOf() prior to any other type cast

    So we could do something like:

    var mixin = {
      valueOf:  function () { return false },
      toString: function () { return 'true' }
    };
    mixin === false;  // false
    mixin == false;    // true
    '' + mixin;       // "false"
    String(mixin)     // "true"
    

    Tested in FF 34.0 and Node 0.10

    0 讨论(0)
  • 2020-12-04 08:49

    On this page you can test the performance of each method yourself :)

    http://jsperf.com/cast-to-string/2

    here, on all machines and browsers, ' "" + str ' is the fastest one, (String)str is the slowest

    0 讨论(0)
提交回复
热议问题