Displaying a pyramid of numbers with JavaScript

Is there a way to create a pyramid number structure in JavaScript?

for (i = 1; i <= 5; i++) {
  var k = ' ';
  var myspace = '';
  for (j = 0; j < i - 0; j++) {
    k += i;
    myspace += ' ';
  }
  console.log(myspace + k);
}

I am trying to achieve this kind of pattern:

    1
   2 2
  3 3 3
 4 4 4 4

Answer №1

Give this code a go:

function buildTriangle(length) {
  for (var i = 0; i < length; i++) {
    var result = '';
    for (var j = 0; j < length - i; j++) result += ' ';
    for (var k = 0; k <= i; k++) result += (i + 1) + ' ';
    console.log(result);
  }
}

buildTriangle(4);

Answer №2

Check out the following solution.

var x;
var y = 10;
for (var a = 0; a <= y; a++) {
  for (var b = 0; b <= a; b++) {
    document.write(b + " ");
  }
  document.write("<br />");
}

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

Do not execute the script if the window's width is below a certain threshold

I have a unique website layout that adjusts to different screen sizes, and I've incorporated some jQuery functionality. Here is a snippet of the code: <script> $(document).ready(function(){ $("#D1000C36LPB3").click(function(){$("#D ...

Encountering a sudden problem while running gulp build due to a node_module - Surprising occurrence of Unexpected

Encountering an unexpected issue while running a gulp build process for a web app that I am struggling to resolve. The problem did not exist on the evening of 25/01/2019, but when attempting to execute the gulp build process this morning (30/01/2019), an ...

Another option to avoid using complicated else if chains

I'm facing a challenge with a function that returns a value known as user_id. It involves multiple conditions that need to be checked. First condition: Verify the service variable Second condition: If not found, retrieve user_id from local storage ...

Methods to troubleshoot problem of angular component loading issue in firefox with ViewEncapsulation.Native

I am encountering a problem with loading an angular component using ViewEncapsulation.Native in firefox, edge, and ipad chrome. Interestingly, there is no issue on safari on mac, chrome on windows, or chrome on android. Error: hostEl.createShadowRoot is ...

The links located beneath the iframe/span element are unclickable

My latest creation is a static advert ticker positioned at the bottom of the window. It's contained within an <iframe> for easy placement on other websites. I added a <span> around the <iframe> to keep it fixed at the bottom of the s ...

Creating a nested tree structure array from a flat array in Node.js

I have an array structure that I need to convert into a tree array using node.js. The current array looks like this: var data= [ { "id1": 1001, "id2": 1002, "id3": 1004, ... } ...

How to utilize AngularJS to submit a Symfony2 form

I'm currently working on developing an application with Symfony2 for the backend and considering using AngularJS for the frontend. My plan is to integrate Symfony forms into the project as well. I have successfully set up the form with all the necessa ...

Is it possible to calculate a variable within a dataset using existing data as a reference point?

Is there a way to dynamically compute some of the data variables in a Vue instance by referencing other variables and tracking their changes? new Vue({ el: '#root', data: { x: 1, y: x + 1 } }) <script src="https://cdnjs.cloudf ...

The data type 'string' cannot be assigned to the data type 'Position'

Currently, I am in the process of converting React js to typescript. The component being used is a Class Component. I would like to obtain CSS settings through props and apply them to an element. How can I resolve this issue? render(){return( <span st ...

What is the best way to use Jquery ScrollTo() to navigate to an element on a page using a class selector

Building on the information from this source, I have a question: How can I resolve the same issue using a class selector like $('.class')? I am encountering an error message that says Uncaught TypeError: undefined is not a function This occurs ...

What is the best approach to handling this situation in React?

I'm currently developing a React application where the user must select a specific character: comma (,) semicolon (;) colon (:) Other If the user selects 'Other,' a new input field appears, allowing the user to input a custom character. A ...

selecting a number at random from a defined array

I am looking to generate a series of lottery numbers like the following: my list could be between 1 - 100, or it might range from 1 - 200, or even 1 - 300 select 35 random numbers from the chosen list. choose another set of 25 numbers from the list. pic ...

Unable to return res.send without encountering errors

There must be a crucial element that I'm overlooking here router.get("/", async (req, res, next) => { let posts = await loadPostsCollection(); console.log(await posts.find({}).toArray()); res.send(await posts.find().toArray()); }); ...

Ensure each alternate div has a unique background hue

While attempting to use CSS to assign a different background color to every second div element, I encountered an issue where both divs were affected when using (odd) and none when using (even). How can this be explained? .hoverDiv:nth-child(odd) { ba ...

Is it possible for inline-block list items to wrap words onto new lines?

I'm working on displaying a series of details within an unordered list inline, but facing an issue with some list items being too long for the relatively small area available. This is the unordered list I'm adding to my view: "<ul class=&apo ...

unable to view the outcome of an ajax request

I am encountering an issue where I am trying to save an AJAX response to the Post PHP variable and display it on the same page. However, I keep getting a "Notice: Undefined index" error. I believe the problem lies in the success part of the AJAX call. Can ...

I encountered an issue with rate-limiter-flexible where I received an error stating that the Lua redis() command arguments need to be either

I have implemented rate limiting using the rate-limiter-flexible library const redis = require('redis'); const { RateLimiterRedis } = require('rate-limiter-flexible'); This is the code snippet I am working with // Create a Redis client ...

The CSS div gradually descends as I increase the width of the browser

I'm in need of assistance with creating a website specifically for mobile devices and tablets. The issue I am facing is that when I expand my browser width to a tablet size, the "loginD" div shifts downwards - view this gif Below is my HTML code: &l ...

Do you have any recommendations for a jQuery plugin that can create a sleek horizontal scrolling image gallery?

Recently, I came across the Smooth div scroll plugin developed by Thomas Kahn, and it fits my requirements perfectly. However, I have encountered a bug that seems to be persisting. The issue arises when both mousewheel scroll and touch scroll are enabled s ...

site.js problem

Recently, I decided to create my very own CS:GO gambling website. After successfully setting it up on my localhost using VPS, I moved on to getting a domain and finalizing everything. However, when attempting to run site.js, an error message popped up: [e ...