Casting to string in JavaScript

前端 未结 8 1726
轻奢々
轻奢々 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条回答
  •  萌比男神i
    2020-12-04 08:36

    There are differences, but they are probably not relevant to your question. For example, the toString prototype does not exist on undefined variables, but you can cast undefined to a string using the other two methods:

    ​var foo;
    
    ​var myString1 = String(foo); // "undefined" as a string
    
    var myString2 = foo + ''; // "undefined" as a string
    
    var myString3 = foo.toString(); // throws an exception
    

    http://jsfiddle.net/f8YwA/

提交回复
热议问题