使用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
。我该如何避免这个问题?
修改:我未正确初始化usersToAppend
和leadsToAppend
。正确的初始化代码是
var usersToAppend = "", var leadsToAppend = "";
答案 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"