js 如何优雅的拼接 字符串

JavaScript032

js 如何优雅的拼接 字符串,第1张

JS中有三种字符串连接方式:

第一种方法 , 用连接符“+”把要连接的字符串连起来:

str="a"str+="b"

第二种方法, 以数组作为中介用 join 连接字符串:

var arr=new Array()arr.push(a)arr.push(b)var str=arr.join("")

第三种方法, 利用对象属性来连接字符串:

function stringConnect(){this._str_=new Array()}stringConnect.prototype.append=function(a){this._str_.push(a)}stringConnect.prototype.toString=function(){return this._str_.join()}var mystr=new stringConnect

mystr.append("a") var str=mystr.toString()

JS中三种字符串连接方式的性能比较:

第一种,方法毫无疑问是最便捷快速的,如果只连接100个以下的字符串建议用这种方法最方便;

第二种,这种方法要比第一种消耗更少的资源,速度也更快;

第三种,方法加入了随机参数,应该是避免了缓存的影响的。

一、使用javascript 模板引擎

用javascript预编译模版,就是动态修改模板文件使之成为一个可用的静态HTML文件。 我平时会使用artTemplate,性能很好而且易上手。

编写模板

使用一个type="text/html"的script标签存放模板:

<script id="test" type="text/html">

<h1>{{title}}</h1>

<ul>

{{each list as value i}}

<li>索引 {{i + 1}} :{{value}}</li>

{{/each}}

</ul>

</script>

渲染模板

var data = {

title: '标签',

list: ['文艺', '博客', '摄影', '电影', '民谣', '旅行', '吉他']

}

var html = template('test', data)

document.getElementById('content').innerHTML = html

二、使用CoffeeScript

CoffeeScript支持类似于Python的跨行字符串,这样很轻易的就能保持HTML结构的可读性,而不需要使用“+”或者采用拼数组的形式。

str="""

<div class="dialog">

<div class="title">

<img src="close.gif" alt="关闭" />关闭

</div>

<div class="content">

<img src="delete.jpg" alt="" />

</div>

<div class="bottom">

<input id="Button2" type="button" value="确定" class="btn"/>

<input id="Button3" type="button" value="取消" class="btn"/>

</div>

</div>

"""