简体   繁体   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>

Let's suppose I have a nD array which its values is dynamically changing.假设我有一个 nD 数组,它的值在动态变化。 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 .例如,如果数字是[x,y,z] ,它应该改变arr[x][y][z] = value notice that we do not know the length of numbers array.请注意,我们不知道numbers数组的长度。 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);
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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