The 8 x 8 grid I am constructing is functional, however, the issue lies in the fact that the first line only begins with a single # symbol

I am attempting to create an 8 x 8 grid. It's coming together, but the issue is that the first line only starts with one # sign.

function print(msg) {
  console.log(msg);
  return msg;
}


let result = "";

for(let i=1; i<=8; i++) {
    result += " #\n"
    for(let j=1; j<8; j++) {
        result += " #";
    }
}

print(result);
// output is
#
 # # # # # # # #
 # # # # # # # #
 # # # # # # # #
 # # # # # # # #
 # # # # # # # #
 # # # # # # # #
 # # # # # # # #
 # # # # # # #

I am trying to build 8 x 8 grid its working but the problem is first line start from only one # sign

Answer №1

There is another method to achieve this task through the use of arrays:

  • Start by creating a new array with 8 elements
  • Next, populate the array with values
  • Map each element in the array to 8 "#" characters
  • Finally, join all elements in the array using "\n"

let result = Array(8).fill().map(_=>"# ".repeat(8)).join("\n")
console.log(result);

Alternatively, you can simply use the repeat function:

let result = ("# ".repeat(8)+"\n").repeat(8);
console.log(result);

Answer №2

Make sure to add the " \n" at the end of the inner loop

function displayMessage(msg) {
    console.log(msg);
    return msg;
}


let output = "";

for(let a=1; a<=8; a++) {
    for(let b=1; b<8; b++) {
        output += " #";
    }
    output += " #\n"
}

displayMessage(output);

Answer №3

To ensure proper formatting, remember to add a \n at the end of the inner for loop.

function print(msg) {
  console.log(msg);
  return msg;
}


let result = "";

for(let i=1; i<=8; i++) {
    
    for(let j=1; j<8; j++) {
        result += " #";
    }
    
    result += " #\n"
}

print(result);

Answer №4

Here is a possible solution:

  for(let x=1; x<=8; x++) {
    output += " #"
    for(let y=1; y<8; y++) {
      output += " #";
    }
    output += "\n";
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experiencing difficulties managing NodeJS session

I've been attempting to integrate a login feature into my nodejs-based web application. const express = require('express'); const app = express(); const route = express.router; const sessions = require("client-sessions"); app.use(sessions ...

Display a modal using jQuery, PHP, and Ajax to verify if a user is

Using a combination of jQuery, PHP, and Ajax, I am able to check if a user is logged in or not. JavaScript: jQuery(document).ready(function() { setInterval(function() { jQuery.ajax({ url: 'chkLoggedin.php', type: 'POST', ...

An unusual error occurred stating that the `forEach` property does not exist on the given type

I am working on a chess game and encountering some Typescript errors that I'm struggling to comprehend. The issue arises in the following class method: clickEvent (e: MouseEvent): void { const coordinates: ClientRect = this.chessBoard.getBounding ...

Padding has an impact on the widths of flexbox items

Take a look at this code snippet: http://jsfiddle.net/56qwuz6o/3/ <div style="display:flex"> <div id="a">a</div> <div id="b">b</div> <div id="c">c</div> </div> div div { ...

Ensure that Ajax requests are successfully executed when a user navigates away from the page

I have developed an HTML/JavaScript application that requires an AJAX request to be made when the user refreshes or closes the page in order to close the application gracefully. To achieve this, I am using the pageunload event. I have implemented the func ...

Managing special characters in PHP: Understanding charsets

While working on my website using HTML and PHP, I am having an issue with special characters (Å, Á ...) appearing as on the screen when using the post function. Strangely enough, all other HTML content displays correctly. Any suggestions for a solution ...

The mechanism for transferring data from the server to the client using JavaScript is malfunctioning

In my webform, I have a fileupload control and a button. When the button is clicked after selecting a file to upload, the image should be saved and renamed with a unique GUID. protected void btnUpload_Click(object sender, EventArgs e) { string fileNam ...

What's the best way to integrate Bootstrap into my HTML document?

Hey there, I'm new to the coding world and just started learning. I could use some assistance with including Bootstrap v5.1 in my HTML code. The online course I'm taking is using an older version of Bootstrap, so I'm having trouble finding t ...

The repairDatabase function cannot be found in the Collection.rawDatabase() method

Seeking guidance on repairing a database within Meteor. Currently executing the following code: Meteor.methods({ 'repairDB'(){ Users.rawDatabase().repairDatabase(); return true; } }); Encountering the following error: I20170630-18: ...

Navigate to the line situated at the exact midpoint vertically

I have a div with child elements, each containing a line of text. <div id="aboutxt"> <div class="line">TEXT_LINE_ONE</div> <div class="line">TEXT_LINE_TWO</div> <div class="line">TEXT_LINE_THREE</div> ...

Tips on harnessing the power of PhantomJS and node.js for web scraping

After successfully installing node-phantom using the command npm install node-phantom, I encountered an error when running this code: Cannot find module 'webpage' var webpage = require('webpage').create(), url = "https://www.exampl ...

How can you utilize jQuery to iterate through nested JSON and retrieve a specific matching index?

In the scenario where I have a nested JSON object like this: var library = { "Gold Rush": { "slides": ["Slide 1 Text","Slide 2 Text","Slide 3 Text","Slide 4 Text"], "bgs":["<img src='1.jpg' />","","<img src='2.j ...

What is the best way to move to a new line without creating a space between the current line and the new line?

I am trying to achieve the desired output: $text = Hello, this is example text. rather than: $text = Hello, this is example text. When I use \n, it starts a new line. How can I make it stay on the same line below with the same startin ...

Sending a CSS class name to a component using Next.js

I am currently in the process of transitioning from a plain ReactJS project to NextJS and I have a question. One aspect that is confusing me is how to effectively utilize CSS within NextJS. The issue I am facing involves a Button component that receives ...

Center a vertically aligned element following a heading, with the content dynamically generated and enclosed in a fixed container

My mind is racing with this problem and I'm not sure if it's solvable, but before throwing in the towel, I thought I'd seek help from the Internet Gods. Here's a visual representation of what I'm aiming for: I want the text to al ...

Encountered an error of 'npm ERR! invalid semver' when attempting to release an npm package

npm ERR! code EBADSEMVER npm ERR! invalid semver: npm ERR! Check out the full log of this run here: I attempted to reinstall node and semver, but unfortunately it did not resolve the issue. ...

What is the proper way to send an AJAX request with the data type set to

I am currently working on creating my own POST request. Below is the function I have written: function sendPost(o) { var h = new XMLHttpRequest(); h.onreadystatechange = requestComplete; function requestComplete() { if (h.readyState = ...

The assets path is the directory within the installed package that houses the main application files following the completion of a

I have a Vue.js UI component that is internally built using webpack. This reusable UI component library references its images as shown below: <img src="./assets/logo.png"/> <img src="./assets/edit-icon.svg"/>   <i ...

Are HTML's Regular Expressions the Equivalent of JavaScript's Regular Expressions?

I have been trying to utilize the pattern="" attribute in HTML to implement regex, but unfortunately, I am unable to locate a comprehensive list of HTML regex parameters. This has led me to ponder whether the syntax for regex in HTML is similar to JavaSc ...

Incorporating ContentPlaceHolder in ASP.NET MasterPage

For my In-Application CMS project, I am considering allowing users to upload an HTML and a CMS file as the Masterpage. One solution I have in mind is to have users include Pre-Defined Tags within their HTML files, which I can then replace with ContentPlac ...