简体   繁体   中英

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>

Let's suppose I have a nD array which its values is dynamically changing. let arr = [[],[],[[],[]],null,[]]; . I need a function which receives an array of numbers, and a value, to change that value of the main array.

/*
 * 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
}

For example if numbers are [x,y,z] , it should change arr[x][y][z] = value . notice that we do not know the length of numbers array. Any suggestion for implementing the function?

You could use recursion to get/change the values;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM