在JavaScript中会经常遇到字符串拼接,但是如果要拼接的字符串过长就比较麻烦了。
如果在一行的话,可读性太差;如果换行的话,会直接报错。
现在就来介绍几个JavaScript拼接字符串的几个小技巧(主要针对字符串过长的情况)。
1. 字符串相加(+)
var empList = '
'+'Hello world'+
'
';2.利用反斜杠拼接字符串
var empList = '
\Hello world\
';3. 利用数组拼接字符串
var empList = ['
', ' Hello world',''].join("");利用数组的join方法,把数组转成字符串
function StringBuffer(){
this.buffer = [];
}
//将新添加的字符串添加到数组中
StringBuffer.prototype.append = function(str){
this.buffer.push(str);
return this;
};
//转成字符串
StringBuffer.prototype.toString = function(){
return this.buffer.join("");
};
//用法
var buffer = new StringBuffer();
buffer.append("hello");
buffer.append(',world');
console.log(buffer.toString());
在数组方法的基础上可以封装一个类似Java中的StringBuffer的类来完成字符串的拼接。
以上所述就是本文的全部内容了,希望大家能够喜欢。