在JavaScript中字符串组合相加,大家一般直接用+拼接起来.例如:
for(i=0; i<len; i++){
if(zdname != ""){
zdname += "#" + trNode.children.item(i).getAttribute("busPath");
}else{
zdname = trNode.children.item(i).getAttribute("busPath");
}
}
这种写法在数据量大的时候是没有问题的,但是如果循环次数太大就存在性能问题,同时在字符串拼接的时候还需要在循环内容做拼接前的判断。下面提供一种用数组拼接的方法。
首先第一个StringBuffer对象
function StringBuffer() {
var _parts = new Array();
}
StringBuffer.prototype.append = function (text) {
if ((text == null) || (typeof(text) == 'undefined')) {
return this;
}
if ((typeof(text) == 'string') && (text.length == 0)) {
return this;
}
_parts.push(text);
return this;
}
StringBuffer.prototype.toString = function(delimiter) {
return _parts.join(delimiter || '');
}
使用的方法是:
var buffer = new StringBuffer();
for(i=0; i<len; i++){
buffer.append(trNode.children.item(i).getAttribute("busPath"));
}
zdname = buffer.toString("#");
这样无论在编写清晰 还是性能都是很不错的选择。