[英]Printing multiplication table with 2D array
我是一个真正的初学者,现在我正在为 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(',', ' | '));
}
这就是我想出的...
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);
generate返回一个类似[fn(0), fn(1), fn(2), ..., fn(num-1)]
的数组。 有不止一种方法可以做到这一点,但我在这里提供的非常快。
表调用generate ,但元素连接在一起形成一个字符串,它们之间有一个分隔符。
entry格式化表格中一个条目的文本,如: 2 x 3 = 6
结果是一张表(二维表),其中|
分隔列和\n
分隔行。
如果您坚持拥有一个完整的 2D 数组,则可以像这样将连接推迟到以后,但速度较慢:
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);
OP没有具体说明乘法表的output应该在什么——HTML,文本,小马......?
表可以由外循环和内循环生成:
外部循环生成表格的数组行。
[row 1, row 2, row 3]
内部循环为每一行生成一个单元格数组(形成一列)。
[col 1, col 2, col 3]
所以一个二维数组看起来像一个数组中的一个或多个 arrays。
[ row 1[col 1, col 2, col 3], row 2[col 1, col 2, col 3], row 3[col 1, col 2, col 3] ]
下面的示例是一个 function ,它将传递一个数字 ( num
) 并返回一个与传递的参数 ( num
) 具有相同数量的行和列的表。 每个单元格将包含一个简单公式的文本:
row number * col number = X
每个col
由 pipe |
分隔。 ,并且每一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 */
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.