JavaScript array dimensionality reduction

let arr22 = [1,2,[3,4],[5,6]];
console.log(Array.prototype.concat.apply([],arr22)) //[1,2,3,4,5,6]

1, first of all look at the apply () and concat () method

  • Other objects .apply method name (the current object, [parameter 1, parameter 2, parameter 3]): the current object to use other objects, and pass parameters.
  • concat (): Array stitching, returns a new array

2, the multi-dimensional array into a one-dimensional dimensionality reduction. First, the n-dimensional array dimensionality reduction is n-1 dimensional, sequentially and recursively, one-dimensional dimensionality reduction.

  Recursive need to know (1) recursively conditions; (2) end conditions. Recursive function passing an array parameter is the time when the array element of the array, recursively; array element of the array is not the time, to push the new array element.

  Analyzing a large array element is not a method of: Array.isArray (ele);

  • Recursive conditions: when there is a time element of the array object array
  • End condition: When there is no element of the array object array
    let arr22 = [1,2,[3,4],[5,6]];
    var newArr = [];
    var f22 = function(arr) {
        for(let i = 0;i < arr.length;i++){
            if(Array.isArray(arr[i])){
                f22(arr[i]);
            }else{
                newArr.push(arr[i]);
            }
        }
    };
    f22(arr22);
    console.log(newArr);

 

Guess you like

Origin www.cnblogs.com/minyDong/p/11516875.html