连接空字符串

时间:2013-04-26 19:31:13

标签: javascript string-concatenation

使用JavaScript时,我遇到了连接空字符串的问题。例如,声明

var usersToAppend, leadsToAppend = "";
$(document).ready(function() {
    console.log(usersToAppend);
    parser = new DOMParser();

    //Get list of users
    var usersXML = parser.parseFromString('<%=WebConnector.getSomeXML()%>', "text/xml");
    console.log(usersXML);
    var users = usersXML.getElementsByTagName("users")[0].childNodes;
    for(var k = 0; k < users.length; k++)
        usersToAppend += users[k].childNodes[0].nodeValue + " -- "+users[k].attributes.getNamedItem("email").nodeValue+"<br>";
});

usersToAppend开头undefined。我该如何避免这个问题?

修改:我未正确初始化usersToAppendleadsToAppend。正确的初始化代码是

var usersToAppend = "", var leadsToAppend = "";

1 个答案:

答案 0 :(得分:6)

您忘记将usersToAppend初始化为空字符串:

var usersToAppend = "", leadsToAppend = "";

空字符串与其他字符串连接正常。问题是当你没有分配任何值时,它被视为undefined并在尝试与另一个字符串连接时强制转换为字符串"undefined"

var foo = '';
foo += 'baz';
console.log(foo); //"baz"

var bar; //no value, treated as undefined
bar += 'baz';
console.log(bar); //"undefinedbaz", undefined coerced to string is "undefined"