var flatten = function(input, shallow, strict, startIndex) { var output = [], idx = 0; for (var i = startIndex || 0, length = input && input.length; i < length; i++) { var value = input[i]; if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) { if (!shallow) value = flatten(value, shallow, strict); var j = 0, len = value.length; output.length += len; while (j < len) { output[idx++] = value[j++]; } } else if (!strict) { output[idx++] = value; } } return output; };
主要是利用了遞歸,首先循環數組,若是數組內部元素是數組,則對其遞歸調用自身函數。不然直接將其值賦給Output數組,原理相似於對象的深度clone函數。javascript
function cloneObject(src) { var obj; if (typeof src === 'object') { // 須要注意的是對typeof對null也返回'object' if (src === null) { obj = null; } else { obj = {}; for (var k in src) { if (src.hasOwnProperty(k)) { obj[k] = (typeof src[k] === 'object') ? cloneObject(src[k]) : src[k]; } } } } else { obj = src; } return obj; }
for (var i = 0, length = array.length; i < length; i++) { var value = array[i]; var result = []; if (!_.contains(result, value)) { result.push(value); } return result;
方法相似於經常使用的去重方法,定義一個空對象,將數組每項的值做爲對象的屬性,檢測對象的屬性是否存在,若是不存在,則將其push到結果數組中,並給這個屬性設值,這樣下次有相同的值,那麼這個屬性就是存在的。這裏是依賴內部的_.contains函數來實現的。java
for (var i = 0, length = array.length; i < length; i++) { var value = array[i]; var result = []; var a = {}; if (!a[value]) { a[value] = 1; result.push(value); } return result;
_.sortedIndex = function(array, obj, iteratee, context) { iteratee = cb(iteratee, context, 1); var value = iteratee(obj); var low = 0, high = array.length; while (low < high) { var mid = Math.floor((low + high) / 2); if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; } return low; };
-ps: 發現_.range裏一個var range = Array(length);這種不加new的,還有其餘庫裏new調用構造函數不加括號的,js真的很靈活。。數組