1

在使用 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 = "";
4

1 回答 1

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"
于 2013-04-26T19:41:15.150 回答