2016-10-28 104 views
3

自从我选择了一门编程课程以来,我一直在浏览它,并发现它是一个很棒的社区,也是知识的绝佳场所。替换<br>

目前我被卡住的JavaScript函数,我试图清理。

我需要将名称输入到数组中,然后当我运行“开始”函数时,它会将名称数量显示为数字,然后在新行上显示每个名称。

我已经设法让它工作,但是在每一行的开头有一个','字符。我尝试了各种方法来解决它(使用替换和分割+连接),但迄今为止没有运气。

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;} 
} 
+2

在'document.getElementById(“output”)。innerHTML =“数组中的总名称是:”+ totalName +“
“+ arrName;'你要把一个数组放入DOM('arrName')。在数组被串化后,在每个元素之间添加','。将'arrName'改为'arrName.join(“
”),然后你可以从'arrName.push(custName +“
”)中移除'
';' – eithed

回答

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 Loop,你可以像这样跳过它:

 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; 
      } 
     } 
0

当控制台登录或插入到DOM直接将被表示为item1,item2,item3,item4

所以,简单地阵列,arrName.join("<br />")

此外,您的while循环可以简单地通过

totalName = arrName.length; count = arrName.length

取代