安全的字符串拼接
假如你需要拼接一些不确定类型的变量为字符串,你需要确保算术运算符在你拼接时不会起作用。使用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" instead of "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