Casting to string in JavaScript

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

    Real world example: I've got a log function that can be called with an arbitrary number of parameters: log("foo is {} and bar is {}", param1, param2). If a DEBUG flag is set to true, the brackets get replaced by the given parameters and the string is passed to console.log(msg). Parameters can and will be Strings, Numbers and whatever may be returned by JSON / AJAX calls, maybe even null.

    • arguments[i].toString() is not an option, because of possible null values (see Connell Watkins answer)
    • JSLint will complain about arguments[i] + "". This may or may not influence a decision on what to use. Some folks strictly adhere to JSLint.
    • In some browsers, concatenating empty strings is a little faster than using string function or string constructor (see JSPerf test in Sammys S. answer). In Opera 12 and Firefox 19, concatenating empty strings is rediculously faster (95% in Firefox 19) - or at least JSPerf says so.

提交回复
热议问题