亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

此矩陣函數返回輸入“'1 2 3\n4 5 6”的列的確切步驟是什么?

此矩陣函數返回輸入“'1 2 3\n4 5 6”的列的確切步驟是什么?

回首憶惘然 2022-01-01 20:10:30
這個矩陣函數返回輸入列的確切步驟是什么'1 2 3\n4 5 6'?function Matrix(input) {  const thisRows =    input.split('\n').map(row => row.split(' ').map(Number));  return {    rows: thisRows,    columns: thisRows[0].map((col,i) => thisRows.map(row => row[i]))  }}我不明白如何thisRows[0].map((col,i) => thisRows.map(row => row[i]))正確返回列,更具體地說,為什么我們使用thisRows[0].
查看完整描述

2 回答

?
MM們

TA貢獻1886條經驗 獲得超2個贊

此函數的輸入將是一個字符串,例如


'1 2 3\n4 5 6'

因此,該函數在 \n 上拆分,返回


['1 2 3', '4 5 6']

然后,該函數循環遍歷數組中的每個項目,并在每個項目上拆分項目' '并將每個子項目轉換為一個數字,返回


[[1, 2, 3], [4, 5, 6]]

該函數然后抓取第一行以獲取矩陣的寬度。該行未被使用,但循環內的索引被使用。然后,在循環內部,循環遍歷每一行并獲取指定索引處的元素,返回列而不是行。


例如。在第一個循環中,索引為 0。在第二個循環中,我們將遍歷每一行并獲取索引為 0 的元素:


i = 0

// first iteration

[1, 2, 3][i] = 1

// second iteration

[4, 5, 6][i] = 4


=> [1, 4]

然后,下一個索引將是 1,所以同樣的事情發生:


i = 1

// first iteration

[1, 2, 3][i] = 2

// second iteration

[4, 5, 6][i] = 5


=> [2, 5]

等等。然后,一旦兩個循環都完成,所有列都將在數組中返回:


[[1, 4], [2, 5], [3, 6]]

這是一個例子,有一些 console.logs 來說明我的意思:


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'))


查看完整回答
反對 回復 2022-01-01
?
MMMHUHU

TA貢獻1834條經驗 獲得超8個贊


const thisRows =

    input.split('\n').map(row => row.split(' ').map(Number));

你有行: [ [1,2,3], [4,5,6] ]


現在要獲取列,您想遍歷第一行并使用 map 函數中當前值的索引來獲取另一個 map 中每一行的值:


i=0 [1,4],

i=1 [2,5],

i=2 [3,6]


查看完整回答
反對 回復 2022-01-01
  • 2 回答
  • 0 關注
  • 215 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號