jquery原始碼——merge 淺度克隆兩個陣列(類陣列);
阿新 • • 發佈:2018-12-10
原始碼及應用:
function merge(first , second) { var i = first.length; var len = i + second.length; var j = 0; for(; i < len; i++){ first[i] = second[j++]; } first.length = len; return first; } var arr = [1,2,3,4,{test: 1}]; var larr = { 0: 1, 1: 2, 2: 3, test: function () { console.log(111); }, length: 3 }; // console.log(merge(arr,larr)); // [1,2,3,1,2,3]; console.log(merge(larr,arr)); // larr = { // 0: 1, // 1: 2, // 2: 3, // 3: 1, // 4: 2, // 5: 3, // 6: 4, // test: function... // length: 7 // }
淺度克隆,若克隆體記憶體在引用值,改變克隆體則會改變被克隆的物件; 如改變 arr[4].test 會改變 larr;