安全的使用字串串接
假設你有一些不確定的變數類型,而你想將它們串接成字串。可以肯定的是,算術運算符不是在串接過程的運用,請使用 concat
:
var one = 1;
var two = 2;
var three = '3';
var result = ''.concat(one, two, three); // "123"
這個方法串接結果是你預期的。相反的,透過加號來串接會造成非預期的結果:
var one = 1;
var two = 2;
var three = '3';
var result = one + two + three; // "33" 而不是 "123"
關於性能部分,與 join
類型比較,串接速度和 concat
是差不多的。
你可以在 MDN 網頁上閱讀到更多關於 concat
函式的資訊。
MEET THE NEW JSTIPS BOOK
You no longer need 10+ years of experience to get your dream job.
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOW
MEET THE NEW JSTIPS BOOK
The book to ace the JavaScript Interview.
A short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW