自从我学习了一门编程课程以来,就已经浏览了一段时间,并发现它是一个很棒的社区和知识的好地方。
目前,我一直在尝试清理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;}
}
原因很可能是因为您尝试
arrName
使用以下代码显示哪个是数组:document.getElementById("output").innerHTML = "The total names in the array are: " + totalName + "<br />" + arrName;
这是我的建议:
var arrName = [];
var custName;
function start(){
var totalName = 0;
var count = 0;
document.getElementById("output").innerHTML = " ";
while(count < arrName.length){
totalName++;
count++;
}
var strOutput = "The total names in the array are: ";
strOutput += totalName + "<br />" + arrName.join("<br />");
document.getElementById("output").innerHTML = " ";
document.getElementById("output").innerHTML = strOutput;
}
function addName(){
custName = document.getElementById("custname").value;
if(!custName){
alert("Empty Name!");
}
else{
arrName.push(custName);
return custName;}
}
由于不需要WHILE循环,因此您可以像这样跳过它:
var arrName = [];
var custName;
function start(){
var totalName = arrName.length;
var strOutput = "The total names in the array are: ";
strOutput += totalName + "<br />" + arrName.join("<br />");
document.getElementById("output").innerHTML = " ";
document.getElementById("output").innerHTML = strOutput;
}
function addName(){
custName = document.getElementById("custname").value;
if(!custName){
alert("Empty Name!");
}
else{
arrName.push(custName);
return custName;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句