2 回答

TA貢獻(xiàn)1886條經(jīng)驗(yàn) 獲得超2個(gè)贊
此函數(shù)的輸入將是一個(gè)字符串,例如
'1 2 3\n4 5 6'
因此,該函數(shù)在 \n 上拆分,返回
['1 2 3', '4 5 6']
然后,該函數(shù)循環(huán)遍歷數(shù)組中的每個(gè)項(xiàng)目,并在每個(gè)項(xiàng)目上拆分項(xiàng)目' '并將每個(gè)子項(xiàng)目轉(zhuǎn)換為一個(gè)數(shù)字,返回
[[1, 2, 3], [4, 5, 6]]
該函數(shù)然后抓取第一行以獲取矩陣的寬度。該行未被使用,但循環(huán)內(nèi)的索引被使用。然后,在循環(huán)內(nèi)部,循環(huán)遍歷每一行并獲取指定索引處的元素,返回列而不是行。
例如。在第一個(gè)循環(huán)中,索引為 0。在第二個(gè)循環(huán)中,我們將遍歷每一行并獲取索引為 0 的元素:
i = 0
// first iteration
[1, 2, 3][i] = 1
// second iteration
[4, 5, 6][i] = 4
=> [1, 4]
然后,下一個(gè)索引將是 1,所以同樣的事情發(fā)生:
i = 1
// first iteration
[1, 2, 3][i] = 2
// second iteration
[4, 5, 6][i] = 5
=> [2, 5]
等等。然后,一旦兩個(gè)循環(huán)都完成,所有列都將在數(shù)組中返回:
[[1, 4], [2, 5], [3, 6]]
這是一個(gè)例子,有一些 console.logs 來(lái)說(shuō)明我的意思:
function Matrix(input) {
const thisRows =
input.split('\n').map(row => row.split(' ').map(Number));
return {
rows: thisRows,
columns: thisRows[0].map((col,i) => {
console.log('index:', i)
return thisRows.map(row => {
console.log('row:', JSON.stringify(row), '\nel:', row[i])
return row[i]
})
})
}
}
console.log(Matrix('1 2 3\n4 5 6'))

TA貢獻(xiàn)1834條經(jīng)驗(yàn) 獲得超8個(gè)贊
后
const thisRows =
input.split('\n').map(row => row.split(' ').map(Number));
你有行: [ [1,2,3], [4,5,6] ]
現(xiàn)在要獲取列,您想遍歷第一行并使用 map 函數(shù)中當(dāng)前值的索引來(lái)獲取另一個(gè) map 中每一行的值:
i=0 [1,4],
i=1 [2,5],
i=2 [3,6]
添加回答
舉報(bào)