簡體   English   中英

如何檢查js中每一行的總和

[英]How to check the sum of every lines in js

好的,如果我有這個:

var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];

我想總結一下:

1 + 2 + 3 && 1 + 4 + 7 && 1 + 5 + 9

像井字游戲一樣,所以我的問題是如何在不用300行代碼填充代碼的情況下做到這一點?

您可以將兩個數組的行和列的起始值作為起始值,並將其作為索引來計算所需的總和。

  15 / 1 2 3 | 6 4 5 6 | 15 7 8 9 | 24 --- --- --- \\ 12 15 18 15 

 var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9"], rows = [0, 3, 6].map(i => [0, 1, 2].reduce((s, j) => s + +array[i + j], 0)), cols = [0, 1, 2].map(i => [0, 3, 6].reduce((s, j) => s + +array[i + j], 0)), slash = [0, 4, 8].reduce((s, i) => s + +array[i], 0), backslash = [2, 4, 6].reduce((s, i) => s + +array[i], 0); console.log(rows); // - console.log(cols); // | console.log(slash); // / console.log(backslash); // \\ 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

假設數組始終為9個條目,則通過手動標識索引最容易做到。 索引是0 ... 8:

0 1 2
3 4 5
6 7 8

然后,我們可以像這樣對行,列和對角線進行建模:

const rows = [
  [0, 1, 2], //Top row
  [3, 4, 5], //Middle row
  [6, 7, 8]  //Bottom row
];

const columns = [
  [0, 3, 6], //Left column
  [1, 4, 7], //Middle column
  [2, 5, 8]  //Right column
];

const bsDiag = [0, 4, 8]; //Backslash diagonal "\"
const fsDiag = [6, 4, 2]; //Forward slash diagonal "/"

然后從數組array提取總和:

const rowSums = rows.map((row, index) => array[row[0]] + array[row[1]] + array[row[2]]);
const columnSums = columns.map((col, index) => array[col[0]] + array[col[1]] + array[col[2]]);
const bsDiagSum = array[bsDiag[0]] + array[bsDiag[1]] + array[bsDiag[2]]
const fsDiagSum = array[fsDiag[0]] + array[fsDiag[1]] + array[fsDiag[2]]

現在,您可以使用

rowSums.forEach((sum, index) => console.log(`Row ${index + 1} has sum: ${sum}`));
columnSums.forEach((sum, index) => console.log(`Column ${index + 1} has sum: ${sum}`));
console.log(`Backslash diagonal has sum ${bsDiagSum}`);
console.log(`Forward slash diagonal has sum ${fsDiagSum}`);

在您的問題中,數組具有字符串值,而不是數字。 該答案假定數組包含數字。 我將保留從字符串到數字的轉換作為Google練習。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM