Home  >  Article  >  Web Front-end  >  Find the multiplication table in Javascript

Find the multiplication table in Javascript

王林
王林Original
2023-05-12 15:46:08704browse

The multiplication table in Javascript

The multiplication table is something we learned in elementary school. It can help us better understand the rules of multiplication and number arrangement. In Javascript, we can use loop statements and nested loop statements to implement the function of the multiplication table.

First of all, we need to clarify the format of the multiplication table. It is a table with 9 rows and 9 columns, and each grid is the result of multiplying two numbers. We can use a double-level loop to implement the output of this table.

The following is the Javascript code to implement the multiplication table:

for (var i = 1; i <= 9; i++) {
  var row = '';
  for (var j = 1; j <= 9; j++) {
    if (i >= j) {
      row += i + '*' + j + '=' + i * j + ' ';
    }
  }
  console.log(row);
}

The first loop in the code is used to control the number of rows, and the second loop is used to control the number of columns. In each inner loop, we will decide whether to output the value of this grid by judging the size relationship between the number of rows and the number of columns. In this way, we can only output the upper triangular digital array.

After executing the above code in the console, you will get the following output:

1*1=1 
2*1=2 2*2=4 
3*1=3 3*2=6 3*3=9 
4*1=4 4*2=8 4*3=12 4*4=16 
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25 
6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 
7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 
8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 
9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81 

In the output, we can find that it only displays the upper triangle digital matrix. This is because we are nesting The loop only outputs grids whose number of rows is greater than or equal to the number of columns. If you want to output the entire multiplication table, just delete the if conditional judgment.

Finally, what we need to pay attention to is that when outputting the multiplication table on the console, we need to ensure that the font size is large enough to ensure the visibility and readability of the entire table.

The above is the detailed content of Find the multiplication table in Javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn