我学习编程课程以来一直在浏览stackoverflow,发现这是一个非常棒的社区和获取知识的好地方。
目前我卡在了一段JavaScript函数上,我正在尝试进行清理。
我需要将名字输入到一个数组中,然后当我运行“开始”函数时,它会显示姓名数量并在新的一行上显示每个姓名。
我已经成功让它工作了,但是每行开头都有一个“,”字符。我尝试了各种方法来解决它(使用replace和split + join),但至今没有成功。
var arrName = [];
var custName;
function start(){
var totalName = 0;
var count = 0;
document.getElementById("output").innerHTML = " ";
while(count < arrName.length){
totalName++;
count++;
};
document.getElementById("output").innerHTML = "The total names in the array are: " + totalName + "<br />" + arrName;
}
function addName(){
custName = document.getElementById("custname").value;
if(!custName){
alert("Empty Name!");
}
else{
arrName.push(custName + "<br>");
return custName;}
}
document.getElementById("output").innerHTML = "The total names in the array are: " + totalName + "<br />" + arrName;
中,你将一个数组放入了 DOM (arrName
)。由于数组被字符串化,,
被添加在每个元素之间。将arrName
改为arrName.join("<br/>")
,然后你可以从arrName.push(custName + "<br>");
中删除<br>
。 - eithed