JavaScript | javascript符號轉換
ExampleUnlikemostotherJavaScriptobjects,symbolsarenotautomaticallyconvertedintoastringwhenperformingconcatenation.letapple=Symbol(Apple)+;//throwsTypeError! Instead,theyhavetobeexplicitlyconvertedintoastringwhennecessary,(forexample,togetatextualdescriptionofthesymbolthatcanbeusedinadebugmessage)usingthetoStringmethodortheStringconstructor.constAPPLE=Symbol(Apple); letstr1=APPLE.toString();//"Symbol(Apple)" letstr2=String(APPLE);//"Symbol(Apple)"
ExampleUnlike most other JavaScript objects, symbols are not automatically converted into a string when performing concatenation.
let apple = Symbol(Apple) + ; // throws TypeError!Instead, they have to be explicitly converted into a string when necessary, (for example, to get a textual description of the symbol that can be used in a debug message) using the toString method or the String constructor.
const APPLE = Symbol(Apple); let str1 = APPLE.toString(); // "Symbol(Apple)" let str2 = String(APPLE); // "Symbol(Apple)"