简体   繁体   中英

How to format output in JavaScript

The script code is for Fibonacci Series. The problem is the output doesn't look good for the eyes. The output is something like this 0,1,1,2,3,5,8,13,21,34,5... . What I want is to format this output and add space after the comma. Is it possible?

<div class="outer">
        <div class="container">
           <button onclick="fibonacci_series(90)">Click To Display Fibonacci Series up to 90</button>
           <p id="demo"> </p>
        </div>
    </div>

    <script>
         var fibonacci_series = function (n) {
            if (n == 1) {
                var loop = [0, 1];
                document.getElementById("demo").innerHTML = loop;
                return loop
            }
            else {
                var s = fibonacci_series(n - 1);
                s.push(s[s.length - 1] + s[s.length - 2]);
                document.getElementById("demo").innerHTML = s;
                return s    
            }
        };
    </script>

What you want can be done with the Array.join(str) method, which connects the items in the array to a specific character.

document.getElementById("demo").innerHTML = s.join(", ");

Below is the result of adding the join method to one line of your code.

 <div class="outer"> <div class="container"> <button onclick="fibonacci_series(90)">Click To Display Fibonacci Series up to 90</button> <p id="demo"> </p> </div> </div> <script> var fibonacci_series = function (n) { if (n == 1) { var loop = [0, 1]; document.getElementById("demo").innerHTML = loop; return loop } else { var s = fibonacci_series(n - 1); s.push(s[s.length - 1] + s[s.length - 2]); document.getElementById("demo").innerHTML = s.join(", "); return s } }; </script>

document.getElementById("demo").innerHTML = s.map(n => <li>${n}</li> ).join("\n");

Below is an example of modifying the code on the same line, and wrapping the li element around the numbers to make it much easier to see.

 <div class="outer"> <div class="container"> <button onclick="fibonacci_series(90)">Click To Display Fibonacci Series up to 90</button> <p id="demo"> </p> </div> </div> <script> var fibonacci_series = function (n) { if (n == 1) { var loop = [0, 1]; document.getElementById("demo").innerHTML = loop; return loop } else { var s = fibonacci_series(n - 1); s.push(s[s.length - 1] + s[s.length - 2]); document.getElementById("demo").innerHTML = s.map(n => `<li>${n}</li>`).join("\n"); return s } }; </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM