Javascript print square using for loop and conditional statement only

后端 未结 4 1596
你的背包
你的背包 2021-01-24 22:13

Just started my uni course, struggling a little with javascript. I have been asked to display a square using any character, however, the solution must combine for loops and if s

4条回答
  •  悲哀的现实
    2021-01-24 22:37

    I'm using console.log to 'print' the square:

        var dimension = 10;
        var edge = '*';
        var inside = ' ';
        var printLine;
    
        for (var i = 1; i <= dimension; i++) {
            if (i === 1 || i === dimension) {
                printline = Array(dimension + 1).join(edge);
            } else {
                printline = edge + Array(dimension - 1).join(inside) + edge;
            }
            console.log(printline);
        }
    

    Note that in the following example, an array of length 11 gets you only 10 "a"s, since Array.join puts the argument between the array elements:

    Array(11).join('a'); // create string with 10 as "aaaaaaaaaa"
    

提交回复
热议问题