Skip to content
Advertisement

unable to print result line by line

I am unable to print result in line by line,it’s coming in one line ,how to solve this…. I tried this code-

<script>
    function know(){
        var num =Number(document.getElementById('number').value);
        var range=Number(document.getElementById('range').value);
        var output="";
        var final=[];
        for(i=1;i<=range;i++)
        {output=i*num;
         final.push(output)
         final=final.replace(",","<br/>")}
        document.getElementById('result').innerHTML=final
    }
</script>

Advertisement

Answer

There is 2 issues in it:

  1. the for loop i you need to declare as a var or let(I recommend let)
  2. there is no replace method in array, you can use map in this case

So you can re write the method like this.

<script>
    function know(){
        var num =Number(document.getElementById('number').value);
        var range=Number(document.getElementById('range').value);
        var output="";
        var final=[];
        //for(i=1;i<=range;i++)
        for(let i=1;i<=range;i++)
        {output=i*num;
         final.push(output)
         //final=final.replace(",","<br/>")
        }
        final = final.map((d, ind) => d*(ind+1))
        document.getElementById('result').innerHTML=final
}
</script>
Advertisement