Casting to string in JavaScript

前端 未结 8 1740
轻奢々
轻奢々 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

提交回复
热议问题