Tips for obtaining the correct Javascript output for the number pyramid

I'm currently in the process of creating a half pyramid of numbers, but I'm facing an issue with getting the output to show the total for each line while maintaining everything except the * sign between the numbers. If anyone is able to offer some assistance, it would be greatly appreciated. Here's the code that I've developed:

<!DOCTYPE html>
<html lang="en>
<head>
    <meta charset="UTF-8">  
    <title>Assignment 1</title>
    <script>
        var num = "";
        var match ="";


var size = prompt("Enter the size of the pyramid");
if (size >=1) {
var total="1";

for(var i=1; i<=size; i++)
{
    if (i < size){
  num = num  +  i + " " 

  } if (i==size) {
  num =num + i }


   total= total * i;
  document.write(num   + " = "+ total + "<br>"); 
}
 }else {
 alert("Please enter a number equal to or greater than 1");
 }
var total="1";
    </script>
</head>
<body>
    <main>
        <!-- Will show after the script has run -->
        <h1>Assignment 1</h1>
    </main>
</body>
</html>

-

I am looking for output like this

1=1
1*2=2
1*2*3=6
1*2*3*4=24
1*2*3*4*5=120

and so on. Thanks again

Answer №1

If you want to calculate the product of numbers using a loop, you can implement it with a slight modification in the iteration:

var result = 1;
var numberList = [];
for(let j=1; j<=6; j++) {
  numberList.push(j);
  result *= j;
  console.log(numberList.join('*') + '=' + result)
}

Output from running the code snippet:

1=1
1*2=2
1*2*3=6
1*2*3*4=24
1*2*3*4*5=120
1*2*3*4*5*6=720

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

Vue - Passing a parent's ref to a child component as a prop

Is there a way to pass the current component's reference to a child component in Vue.js? <template> <div class="screen" ref="screen"> <child-component :screenRef="screenRef"> </child-component> </div ...

Having trouble passing a JavaScript variable through AJAX requests

In this particular script, I am encountering an issue where the variable "encrypted" is expected to be sent via ajax to upload.php, however I am unable to achieve this. Oddly enough, if I substitute the "encrypted" variable with another variable in the a ...

Once the promise program enters the if-condition, even though the condition itself is actually false

There seems to be an issue with retrieving the location code using the AccuWeather API before getting the weather data for a city. Despite the location array being empty, the program still proceeds to a branch that expects a non-empty array. router.get(& ...

Creating a Drop-Down Button Using HTML, CSS, and JavaScript

I am currently working with the following code: <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=PT+Sans ...

Struggling to make Tumblr Javascript function properly

I have integrated the following code snippet: <script type="text/javascript" src="http://underlineent.tumblr.com/api/read/json"> </script> Unfortunately, my Tumblr blog is not appearing on this site. Can anyone provide assistance? The provid ...

JS issue: Having trouble accessing the array values despite the array being present

I am working on an ajax call where I save the success data in an array. However, when I try to access that data outside of the ajax function and use console to log my array, it appears as expected. Here is a glimpse at what I see on the screen: https://i ...

Update the current value in array.prototype

Recently, I've noticed that the built-in JavaScript sort function can be unreliable at times. To address this issue, I decided to create my own sorting function. Consider the following scenario: Array.prototype.customSort = function(sortFunction, upd ...

Determining if a user is already logged in from a different device using express-session

After a user logs in, I assign the username to their session with the code: req.session.username = "...."; This identifies the session with a username, but now I need to figure out how to detect if this same username is already logged in from another dev ...

What is the encoding for Javascript in UTF-8?

My current ajax call is able to successfully send the request and retrieve the expected response. However, I am facing difficulty in correctly displaying it in li items. $.ajax({ url: "{% url 'users:profile_page_tags_get' 'primary&apos ...

Introduce an additional parameter to the Prestashop Cart entity

After setting up a radiobox "stock_action" in the Cart, I need to send its value to the Cart object for additional order costs. In the Cart Override, the $stock_action variable has been added: public $stock_action; /** * @see ObjectModel::$defi ...

Updating the default date format input fields for React-bootstrap-daterangepicker in the United States

Hey there, I'm a newcomer to the world of React and Javascript and I've encountered an issue that has me stumped. I'm trying to change the default US dateformat in my React-bootstrap-daterangepicker, but I'm struggling to figure out how ...

tips for sending types as properties in a versatile component

I am facing a challenge with passing types as props to a reusable component. I have a component where I pass rows and headings as props, but I need to find a way to pass types as props as well. Below is the code for my reusable component: import { TableCe ...

Changing the colors of multiple buttons in a React Redux form: a step-by-step guide

When using Redux Form Wizard on the second page, I have two buttons that ask for the user's gender - Male or Female. The goal is to make it so that when a user clicks on either button, only that specific button will turn orange from black text. You ...

extracting the ID from within an iframe

Currently, I am developing a script using pure javascript. parent.*nameofiframe*.document.getElementById('error').value; However, when attempting to achieve the same using jQuery, it doesn't seem to work: $('*nameofiframe*', win ...

`Setting the response as an ArrayBuffer can be achieved on the client side, but it cannot be

I am working on a client-side form where I use XMLHTTPResponse to save response data as a file. In order to achieve this, the response type is set to arraybuffer using the following code: xhr.responseType = "arraybuffer"; While researching various method ...

After refreshing, the LocalStorage in Angular 2 seems to disappear

Something a little different here :) So, when attempting to log a user in, I am trying to store the access_token and expires in localStorage. It seems to be working "okay". However, if I refresh the page, the tokens disappear. Also, after clicking the log ...

How come my variable doesn't show up in the view even though I filled it in the controller?

I'm having trouble with my AngularJS setup. The angular.min.js file is located in the js folder, following a code example from O'Reilly's book. However, for some reason it is not working on my computer. //controller.js function HelloCont ...

A comprehensive guide on organizing JavaScript files within an Angular project

In the process of building my MEAN app, I have structured my folders in the following way: I have included a js file in /angular/src/assets/js for jQuery functionalities. To achieve this, I utilized npm to install jQuery. Now, I am faced with the task o ...

Having issues with React Nivo tooltip functionality not functioning properly on specific graphs

While using Nivo ResponsivePie to visualize some data, everything is functioning properly except for the tooltip. For some reason, the tooltip isn't appearing as it should. Interestingly, I have a heatmap and a bar graph with tooltips that are working ...

Signing in using Passport.js with mongoDB authentication

Apologies if this question appears redundant, but I am struggling to resolve an issue with a "MISSING CREDENTIALS" error when trying to implement user login using email and password. Despite going through numerous responses, none have provided a solution. ...