自从我选择编程课程以来,已经浏览了一段时间,并且发现它是一个非常棒的社区和知识的好地方。
目前,我一直在使用我正在尝试清理的JavaScript功能。
我需要将名称输入到数组中,然后当我运行' start'函数,它会将名称的数量显示为数字,然后在新行上显示每个名称。
我设法让它发挥作用,但有一个''每行开头的字符。我已经尝试了各种方法来解决它(使用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;}
}
答案 0 :(得分:0)
原因很可能是因为您尝试使用以下代码显示
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;
}
}
答案 1 :(得分:0)
控制台直接记录或直接插入DOM时的数组将表示为item1,item2,item3,item4
简单地说,arrName.join("<br />")
此外,您的while
循环可以简单地替换为
totalName = arrName.length;
count = arrName.length