用二维数组打印乘法 table

Printing multiplication table with 2D array

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

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

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 个变量: 常量 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(',', ' | '));
}

这是我想出的...

n = 3;
// create table array
table = [];
for(row=0; row<n;row++){
    // generate an array for each row
    table.push([])
    for(col=0; col<n;col++){
        // add the multiplication to each column in the row
        // Notice that the column and row numbers start at zero in an array so 1 is added before multiplying
        table[row].push((col+1) + ' x ' + (row+1) + ' = ' + (col+1)*(row+1));
    }
}
// print the array to the console for fun
console.log(table);
// go through each row in table array, convert it to a string and replace ',' with ' | ' and printing it to the log
// Notice that in the replace argument you have to use /,/g instead of ',' in order to replace all commas and not just the first one
for(row=0; row<table.length;row++){ 
    console.log(String(table[row]).replace(/,/g, ' | '))
}

我添加了一些评论。希望你能看到发生了什么。

您需要两个 'for' 循环来填充二维数组。之后,您需要另一个 'for' 循环来打印每一行(例如在段落标记中)。

工作示例:

const n = 3; 
const calc = [];

for(i = 0; i < n; i++){
    calc[i] = [];         //add the inner arrays (the second dimension)
    for(k = 0; k < n; k++){ 
        calc[i][k] = (k + 1) + ' x ' + (i + 1) + ' = ' + (k + 1) * (i + 1);
    }
}

for(i = 0; i < calc.length; i++){ 
    const p = document.createElement("p");
                          //convert each inner array to a string
    p.innerHTML = String(calc[i]).replaceAll(',', ' | ');
    document.querySelector('#container').appendChild(p);
}
<div id="container"></div>

这是我为解决您的问题而编写的代码。

function generate(num, fn) {
  var a = Array(num), b = 0;
  while (b < num) a[b] = fn(b++);
  return a;
}
const table = (num, fn, separator) => generate(num, fn).join(separator);
const entry = (a, b) => `${a} x ${b} = ${a * b}`;
const result = table(3, row => table(3, col => entry(row + 1, col + 1), ' | '), '\n');

console.log(result);

生成 returns 一个像[fn(0), fn(1), fn(2), ..., fn(num-1)] 这样的数组。有不止一种方法可以做到这一点,但我在这里提供的是 pretty quick.

table 调用 generate,但元素连接在一起成为一个字符串,它们之间有一个分隔符。

entry 将 table 中一个条目的文本格式化为:2 x 3 = 6

结果是 table 的 table(二维 table),其中 | 分隔列,\n 分隔行.

注:

如果你坚持要有一个完整的二维数组,你可以像这样推迟连接,但速度较慢:

function generate(num, fn) {
  var array = Array(num), i = 0;
  while (i < num) array[i] = fn(i++);
  return array;
}
const entry = (a, b) => `${a} x ${b} = ${a * b}`;
const array2d = generate(3, row => generate(3, col => entry(row + 1, col + 1)));
const result = array2d.map(row => row.join(' | ')).join('\n');

console.log(result);

1 个行循环和 1 个列循环

OP 没有具体说明乘法 table 的输出应该在 -- HTML、文本、小马...?

一个table可以通过一个外循环和一个内循环生成:

  1. 外循环生成一个table.
    的数组行 [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) 并且 return 一个 table 具有与传递的参数相同的行数和列数 (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
*/

参考资料