1

How can I use break line in my output? There is something wrong in document.write.

Please review my code and give me best solution..

<html>
<head>
    <script type="text/javascript">
    function FahToCent (degFah)
    {
        var degCent = new Array ();

        for (var loopCounter = 0;  loopCounter <=2; loopCounter++)
        {
            degCent[loopCounter] = 5/9 * (degFah[loopCounter] - 32);
        }

        return degCent;
    }
    </script>
</head>
<body>
    <script type="text/javascript">
    var degFah = new Array ();

    for (var loopCounter = 0; loopCounter <= 2; loopCounter++)
    {
        degFah[loopCounter] = prompt ("Enter Temperature in Fahrenheit");
    }

    document.write (FahToCent (degFah)+"<br>");
    </script>
</body>
</html>
Sangbok Lee
  • 2,132
  • 3
  • 15
  • 33
Muhammad Ali Khamis
  • 363
  • 1
  • 3
  • 11

4 Answers4

2

use this

 function FahToCent (degFah)
{
    return 5/9 * (degFah - 32);;
}

var degFah = new Array ();
for (var loopCounter = 0; loopCounter <= 2; loopCounter++)
{
    degFah[loopCounter] = prompt ("Enter Temperature in Fahrenheit");
    document.write(FahToCent (degFah[loopCounter])+"<br>");   
}

Example Link : http://jsfiddle.net/pradkumar_n/Bucjz/

NPKR
  • 5,368
  • 4
  • 31
  • 48
2

just add break tag in your function FahtoCent

 degCent[loopCounter] = 5/9 * (degFah[loopCounter] - 32)+"<BR>";
Senthil
  • 1,244
  • 10
  • 25
1

You've defined degCent as an Array, which is passed to document.write() as an argument. This argument is supposed to be a string, and now it's an array. Hence it's automatically converted to a string before outputting, using Array.toString() method. This method returns a comma-separated list of array values (as a string).

However, you can convert the returned array to a string, and add linebreaks with the same manouver, using an Array-method called join(). Like this:

document.write(FahToCent(degFah).join('<br/>'));

However, document.write() is considered as a bad practise for DOM manipulations. Please check some advanced methods to show the output in the document:

MDN: innerHTML, MDN: appendChild()

Teemu
  • 22,918
  • 7
  • 53
  • 106
-2

I'm not altogether certain of what you are asking here but I think you just want to go to a new line after the code runs. In which case you need writeline rather than write and remove "br" tag

document.writeline (FahToCent (degFah));
gallie
  • 143
  • 1
  • 2
  • 9
  • Caution to anyone reading this answer. The `document.writeline` method does not exist. I'll give the original poster the benefit of the doubt and assume they meant `document.writeln`. But they really should've made sure the method actually exists and was spelled correctly before using it in an answer. – mikeym May 28 '17 at 22:31