将多维数组(尤为是二维数组)转化为一维数组是业务开发中的经常使用逻辑,除了使用朴素的循环转换之外,咱们还能够利用Javascript的语言特性实现更为简洁优雅的转换。本文将从朴素的循环转换开始,逐一介绍三种经常使用的转换方法,并借此简单回顾Array.prototype.concat方法和Function.prototype.apply方法。
如下代码将以把二维数组降维到一维数组为例。数组
1. 朴素的转换app
function reduceDimension(arr) { var reduced = []; for (var i = 0; i < arr.length; i++) { for (var j = 0; j < arr[i].length; j++) { reduced.push(arr[i][j]); } } return reduced; }
此方法思路简单,利用双重循环遍历二维数组中的每一个元素并放到新数组中。ide
2. 利用concat转换
先来回顾一下MDN上对于该方法的介绍:
"concat creates a new array consisting of the elements in the object on which it is called, followed in order by, for each argument, the elements of that argument (if the argument is an array) or the argument itself (if the argument is not an array)."
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat函数
即若是concat方法的参数是一个元素,该元素会被直接插入到新数组中;若是参数是一个数组,该数组的各个元素将被插入到新数组中;将该特性应用到代码中:优化
function reduceDimension(arr) { var reduced = []; for (var i = 0; i < arr.length; i++){ reduced = reduced.concat(arr[i]); } return reduced; }
arr的每个元素都是一个数组,做为concat方法的参数,数组中的每个子元素又都会被独立插入进新数组。
利用concat方法,咱们将双重循环简化为了单重循环。this
3. 利用apply和concat转换
按照惯例,先来回顾一下MDN上对于apply方法的介绍:
"The apply() method calls a function with a given this value and arguments provided as an array."
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/applyspa
即apply方法会调用一个函数,apply方法的第一个参数会做为被调用函数的this值,apply方法的第二个参数(一个数组,或类数组的对象)会做为被调用对象的arguments值,也就是说该数组的各个元素将会依次成为被调用函数的各个参数;将该特性应用到代码中:prototype
function reduceDimension(arr) { return Array.prototype.concat.apply([], arr); }
arr做为apply方法的第二个参数,自己是一个数组,数组中的每个元素(仍是数组,即二维数组的第二维)会被做为参数依次传入到concat中,效果等同于[].concat([1,2], [3,4], [5,6])。
利用apply方法,咱们将单重循环优化为了一行代码,很简洁有型有木有啊~code
读者也可参照本文思路,本身利用递归实现N维数组降维的逻辑。对象
(全文完)