第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何修改n維數(shù)組元素的值,其中索引由Javascript中的數(shù)組指定

如何修改n維數(shù)組元素的值,其中索引由Javascript中的數(shù)組指定

桃花長(zhǎng)相依 2022-07-01 16:20:24
我有一個(gè) n 維數(shù)組,我想使用另一個(gè)數(shù)組來(lái)訪問(wèn)/修改其中的一個(gè)元素來(lái)指定索引。我想出了如何訪問(wèn)一個(gè)值,但是我不知道如何修改原始值。// Arbitrary values and shapearr = [[[8, 5, 8],        [9, 9, 9],        [0, 0, 1]],       [[7, 8, 2],        [9, 8, 3],        [9, 5, 6]]];// Arbitrary values and lengthindex = [1, 2, 0];// The following finds the value of arr[1][2][0]// Where [1][2][0] is specified by the array "index"tmp=arr.concat();for(i = 0; i < index.length - 1; i++){  tmp = tmp[index[i]];}// The correct result of 9 is returnedresult = tmp[index[index.length - 1]];如何修改數(shù)組中的值?是否有更好/更有效的方法來(lái)訪問(wèn)值?
查看完整描述

3 回答

?
喵喵時(shí)光機(jī)

TA貢獻(xiàn)1846條經(jīng)驗(yàn) 獲得超7個(gè)贊

這是一個(gè)經(jīng)典的遞歸算法,因?yàn)槊總€(gè)步驟都包含相同的算法:

  • 從索引中彈出第一個(gè)索引。

  • 繼續(xù)使用新彈出的索引指向的數(shù)組。

直到你到達(dá)最后一個(gè)元素indices- 然后替換最低級(jí)別數(shù)組中的相關(guān)元素。

function getUpdatedArray(inputArray, indices, valueToReplace) {

  const ans = [...inputArray];

  const nextIndices = [...indices];

  const currIndex = nextIndices.shift();

  let newValue = valueToReplace;


  if (nextIndices.length > 0) {

    newValue = getUpdatedArray(

      inputArray[currIndex],

      nextIndices,

      valueToReplace,

    );

  } else if (Array.isArray(inputArray[currIndex])) {

    throw new Error('Indices array points an array');

  }


  ans.splice(currIndex, 1, newValue);

  return ans;

}


const arr = [

  [

    [8, 5, 8],

    [9, 9, 9],

    [0, 0, 1]

  ],


  [

    [7, 8, 2],

    [9, 8, 3],

    [9, 5, 6]

  ]

];

const indices = [1, 2, 0];

const newArr = getUpdatedArray(arr, indices, 100)

console.log(newArr);


查看完整回答
反對(duì) 回復(fù) 2022-07-01
?
蝴蝶刀刀

TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超8個(gè)贊

您可以像這樣更改數(shù)組中的值,

arr[x][y][z] = value;

這有幫助嗎?



查看完整回答
反對(duì) 回復(fù) 2022-07-01
?
慕田峪9158850

TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超7個(gè)贊

我認(rèn)為您正在尋找的是:

arr[index[0]][index[1]][index[2]] = value;

我無(wú)法理解您在示例的第二部分中嘗試做什么。


查看完整回答
反對(duì) 回復(fù) 2022-07-01
  • 3 回答
  • 0 關(guān)注
  • 133 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)