`
yiminghe
  • 浏览: 1432396 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

嵌套数组的平坦化

阅读更多

问题:


jquery中大量用到了 array-like 的操作,不可避免遇到了数组嵌套的问题:

 

var x=[1,2,[3,4]];

 

这样的话,就不容易 each 循环操作了,所以需要转化为

 

var x=[1,2,3,4];

 

jquery 经常遇到的是 一维数组中添加元素,而元素又可能是一维数组的情况,如果每一步结果都转化位一维数组,则只需考虑两维数组的嵌套化问题,则

 

var x=[1,2,[3,4,[7,8]]];

 

不在考虑之列。(这种情况当然可以递归处理得到结果)



解决:


首先要看 apply ,它的第二个参数恰好要求是数组形式,则很幸运的处理了结果数组的第一层嵌套 :


function.apply(thisobj, args)

thisobj


The object to which function is to be applied. In the body of the function, thisobj becomes the value of the this keyword. If this argument is null, the global object is used.

args


An array of values to be passed as arguments to function.

Returns

Whatever value is returned by the invocation of function.

另一方面 ,数组的  concat 方法 ,可能变长参数传入,并且参数为数组时自动循环参数数组操作:


concat( ) creates and returns a new array that is the result of concatenating each of its arguments to array. It does not modify array. If any of the arguments to concat( ) is itself an array, the elements of that array are concatenated, rather than the array itself.



结果代码:


于是就有了jquery map 中非常巧妙的平坦化操作 :

 

var x=[1,2,[3,4]];
alert(x.join("|"));
alert([].concat(x).join("|"));
//正确结果
alert(x.concat.apply([],x).join("|"));
 

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics