簡體   English   中英

更改多維數組 JavaScript 的值

[英]Change values of multidimensional array JavaScript

 var arr = [[],[],null,[[],[]],[[[]]]]; $( document ).ready(function() { addChild(arr, 'main'); }); function inscribe(numbers, value) { while(numbers.length>1){ arr = arr[numbers.shift()]; } arr[numbers.shift()] = value; addChild(arr, 'main'); } function addChild(subarr, id) { var el = document.getElementById(id); var ul = document.createElement("ul"); el.appendChild(ul); subarr.forEach(function(item, index){ var node = document.createElement("div"); var textnode = document.createTextNode(id + '-' + index); node.appendChild(textnode); node.id = id + '-' + index; ul.appendChild(node); if(item && item.length) addChild(item, node.id); }) }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="main"> </div> <button onclick="inscribe([3,1], [[]])">inscribe([3,1], [[]])</button>

假設我有一個 nD 數組,它的值在動態變化。 let arr = [[],[],[[],[]],null,[]]; . 我需要一個接收數字數組和值的函數來更改主數組的值。

/*
 * numbers: an array of integers which indicates which element of array should be set
 * value: the value that should be set
 */
inscribe(numbers, value) {
   // set value for desired position
}

例如,如果數字是[x,y,z] ,它應該改變arr[x][y][z] = value 請注意,我們不知道numbers數組的長度。 對實現該功能有什么建議嗎?

您可以使用遞歸來獲取/更改值;

function inscribe(arr, path, value){
   if(path.length == 1){
      arr[path[0]] = value;
   }else{
      var next = path.shift();
      inscribe(arr[next], path, value);
   }
}

暫無
暫無

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

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