In general, we will first create a one-dimensional array, then reference the two-dimensional array in this one-dimensional array... until the n-dimensional array, and then fill its content with the default value. Sometimes, we need to create a multi-dimensional array and initialize it to the default value we want.
In general, we will first create a one-dimensional array, then reference the two-dimensional array in this one-dimensional array... until the n-dimensional array, and then fill its content with the default value.
In this process, we need to write a lot of loops, which is difficult to avoid. So, why not try to write a multi-dimensional array initialization tool for us to call?
I guess you must want this method:
dim( d1 [,d2 [,d3 [... ]]], value )
Let's look at its parameter list. d1, d2, and d3 represent the number of elements referenced by each dimension array, and value represents the initial value.
This value may be a function. In this case, we reference the return value of the function.
Let's take a look at several examples:
dim( 3,3,"x" ) // => [['x','x','x'],['x','x','x'],['x','x','x']]
Here, an array references three two-dimensional arrays. each two-dimensional array references three initialization values 'x'
dim( 2,2,2,0 ) // => [[[0,0],[0,0]],[[0,0],[0,0]]]
The rules are the same as above.
dim( 3, true ) // => [true,true,true]
Here, the one-dimensional array references three boolean values: true
var xxx = function(){ return "xX" }dim( 2,5,xxx ) // => [['xX','xX','xX','xX','xX'],['xX','xX','xX','xX','xX']]
The initialization value here is a function, so we fill in the result it returns
This question involves n-dimensional arrays, so recursion is required.
It is a process of constructing an array and traversing the edge in depth.
In my method, a parameter deep is used to record the current depth.
For example, dim (,). If the current deep is 0, it corresponds to the first parameter 2, indicating that two arrays should be created, that is, the value of deep is consistent with the index of the parameter list, which indicates the number of arrays or values to be constructed.
If deep reaches the deepest level, initialization can be performed, and the for loop is filled with the current array.
Function dim () {var len = arguments. length; var args = Array. prototype. slice. call (arguments, 0, len-1); var content = arguments [len-1]; var result = []; var traverse = function foo (from, deep) {var arg = args [deep]; if (deep <args. length-1) {for (var I = 0; IThe above is the JavaScript interesting question: multi-dimensional array initialization content. For more information, please follow the PHP Chinese Network (www.php1.cn )!