underscorejs-partition学习

时间:2022-11-02 18:51:10

2.25 partition

2.25.1 语法:

_.partition(list, predicate, [context])

2.25.2 说明:

拆分list为两个数组。

第一个数组的元素都满足predicate, 而第二个数组的所有元素为不能满足predicate。

2.25.3 代码示例:

示例一:拆数组

var arr1 = _.partition([1, 2, 3, 4], function(element, index, list){
return element % 2 === 0;
});
console.log(arr1);//=> [[2, 4],[1, 3]];

示例二:拆对象

var arr2 = _.partition({a:1, b:2, c:3, d:4}, function(value, key, list){
return value % 2 === 0;
});
console.log(arr2);//=> [[2, 4],[1, 3]];

示例三:拆字符串

var arr2 = _.partition('1234', function(value, key, list){
console.log(list); //=> String 1234
return value % 2 === 0;
});
console.log(arr2);//=> [["2", "4"],["1", "3"]];

示例四:拆arguments

(function(){
var result = _.partition(arguments, function(value, key, list){
return value % 2 === 0;
});
console.log(result);//=> [["2", "4"],["1", "3"]];
}(1, 2, 3, 4));

2.25.4 默认的predicate

var list = [1, false, true, '', null, 0, '0'];
var result = _.partition(list);
console.log(result); //=> [[1, true, "0"], [false, "", null, 0]]; //值是对象
var oList = [{x: 1},{x: 1},{x: 0}];
var arr1 = _.partition(oList);
var arr2 = _.partition(oList, 'x');
console.log(arr1); //=> [[{x: 1},{x: 1},{x: 0}],[]]
console.log(arr2); //=> [[{x: 1},{x: 1}],[{x: 0}]]

2.25.5 写出于默认一样的predicate(坑)

var list = [1, false, true, '', null, 0, '0'];
var result = _.partition(list);
var predicate = function(element, index, list){
//请在这里补充代码
};
console.log(result); //=> [[1, true, "0"], [false, "", null, 0]];

2.25.6 拆分奇偶的另一种写法(坑)

var arr1 = _.partition([1, 2, 3, 4], function(element, index, list){
return element & 1; // &是什么鬼,这么厉害!
});
console.log(arr1);//=> [[1, 3], [2, 4]];