首页 > 解决方案 > 用二维数组打印乘法表

问题描述

我是一个真正的初学者,现在我正在为 JavaScript 训练营做准备。不幸的是,我坚持进行一项工作前练习。

我的任务是做乘法表,将其放入空的二维数组中并以这种形式精确打印:

1 x 1 = 1 | 1 x 2 = 2 | 1 x 3 = 3
2 x 1 = 2 | 2 x 2 = 4 | 2 x 3 = 6
3 x 1 = 3 | 3 x 2 = 6 | 3 x 3 = 9

开始时我声明了 2 个 var: const n = 3; 常量计算 = [];

我知道我必须从“for”循环开始——我不知道接下来会发生什么;

for (让 i = 1; i <= n; i++) { }

编辑:感谢您的帮助,下面的正确代码:

const n = 3;
const calc = [];


for(let i = 0; i < n; i++){
    calc[i] = [];
    for(let k = 0; k < n; k++){
        calc[i][k] = (i + 1) + ' * ' + (k + 1) + ' = ' + (i + 1) * (k + 1);
    }
}
for(let i = 0; i < calc.length; i++){
    console.log(String(calc[i]).replaceAll(',', ' | '));
}

标签: javascriptarraysfor-loopmultiplication

解决方案


1 行循环和 1 列循环

OP没有具体说明乘法表的输出应该是什么——HTML、文本、小马......?

表可以由外循环和内循环生成:

  1. 外部循环生成表格的数组行。
    [row 1, row 2, row 3]

  2. 内部循环为每一行生成一个单元格数组(形成一列)。
    [col 1, col 2, col 3]

  3. 因此,二维数组看起来就像一个数组中的一个或多个数组。
    [ row 1[col 1, col 2, col 3], row 2[col 1, col 2, col 3], row 3[col 1, col 2, col 3] ]

下面的示例是一个函数,它将传递一个数字 ( num),并返回一个与传递的参数 ( ) 具有相同行数和列数的表num。每个单元格将包含一个简单公式的文本:

row number * col number = X

每个col都由一个管道分隔|,每个row都由一个新行分隔。

细节在片段中评论

// Pass a number [num]
function mTable(num) {
  // Declare [row] array [rData]
  const rData = [];
  // for each [row] until [num] is reached...
  for (let row = 1; row <= num; row++) {
    //... declare [col] array [cData]...
    const cData = [];
    //... then for each [col] until [num] is reached...
    for (let col = 1; col <= num; col++) {
      //... generate the text✱ repesenting the product of the row and column numbers...
      const cell = `${row} X ${col} = ${row*col}`;
      //... next, push it to the [cData] array
      cData.push(cell);
    }
    // Once the [cData] is created, convert it into a formatted line of text delimited by pipes '|'
    const data = cData.join(' | ');
    // Push the [cData] array into the [rData] array
    rData.push(data);
  }
  // After the last [cData] array is pushed into the [tData] array, output [tData] as a formatted line of text delimited by new lines✱
  return rData.join(`
`);
}

// Generate a 3x3 table 
console.log(mTable(3));

// Generate a 8x8 table
console.log(mTable(8));

/* 
✱The special syntax wrapped in grave ticks `...` is called template literals see References
*/

参考


推荐阅读