jQuery.merge 源码阅读

jQuery.merge(first,second)

概述

  • 合并两个数组

    返回的结果会修改第一个数组的内容——第一个数组的元素后面跟着第二个数组的元素。

参数

  • first:第一个待处理数组,会改变其中的元素。
    second:第二个待处理数组,不会改变其中的元素。

示例

  • $.merge( [0,1,2], [2,3,4] )
  • $.merge( {name:'andrew',age:'23'}, [2,3,4] )  //看看会如何

结果

  • [0,1,2,2,3,4]
  • {name: "Andrew", age: "23", NaN: 3, length: NaN}

源码阅读

 1 function (first, second) {
 2     var l = second.length,
 3         i = first.length,
 4         j = 0;
 5 
 6     if (typeof l === "number") {
 7         for (; j < l; j++) {
 8             first[i++] = second[j];
 9         }
10 
11     } else {
12         while (second[j] !== undefined) {
13             first[i++] = second[j++];
14         }
15     }
16 
17     first.length = i;
18 
19     return first;
20 }

解读

javascript松散的类型结构使得对数组的操作会比较优雅,数组不会越界,不用担心数组长度的问题,仅仅需要对传入类型进行判断。

如果传入是key-value的对象,length会返回undefined,按下标取也会返回undefined。读者可以想想为什么第二个merge会返回这样的结果?

如果传入的是数组的对象,length会正常返回。

原文地址:https://www.cnblogs.com/andrew-chen/p/5408463.html