underscore.js 源码分析(七)
flatten without union intersection uniqflatten
实例
使用flatten 用来将多层嵌套的数组转化为一层,例如:1 | list = [1, [3, 4]]; |
源码分析
1 | _.flatten = function(array, shallow) { |
flatten 函数如下:1 | /* |
without
实例
_.without(array, values)使用 _.without 用来所有 values 值后的 array 副本。使用:1 | _.without([1, 2, 3], 1) |
源码分析
自己写的函数:1 | function without(array, values) { |
undefined原因: 使用 filter方法中的 return 只会跳出 filter 循环,不会跳出最终的函数循环。 低级错误1 | function without(array, values) { |
1 | _.without = function(array) { |
_.difference 的方法实现。使用 _.difference 实现的函数代码如下:1 | _.difference = function(array) { |
union
实例
_.union(*arrays)使用 union 用于返回传入的 arrays 的并集。按照顺序返回,可以传入一个或者多个的 arrays 数组。源码分析
1 | _.union = function() { |
_.uniq 函数如下:1 | _.uniq = _.unique = function(array, isSorted, iteratee, context) { |
intersection
_.intersection(arrays)实例
使用_.intersection 用来返回传入多个数组的并集。1 | _.intersection([1, 2, 3], [1, 2, 4], [10, 1, 2, 6]) // [1, 2] |
源码分析
1 | _.intersection = function(array) { |
result数组,最后将这个 result 数组返回。要点:- 两次循环, 使用结束循环的方式是不一样的。
使用break的时候, 结束的是整个循环使用continue的时候, 结束的是当前的循环
- 关于
contain函数使用contain用来判断在一个数组中是否包含有某一个元素:在es6中使用Array.includes(item)来判断item是否包含在Array之中。
difference
实例
_.difference(array, *others) 使用 difference 获取到来自于 array 但是不存在于 others 中的数组元素。源码分析
自己写的代码:1 | function difference(array, other) { |
1 | _.difference = function(array) { |