_.reject(list, predicate, [context])
前边我们已经学习了filter方法,那么我们在学习reject之前,先让我们来想一下reject和filter有什么关系呢?
filter返回一个的集合(匹配成功),reject是返回一个集合(匹配失败)
对list集合的每个成员依次进行匹配(根据predicate迭代函数检测),返回匹配失败的集合
var result;
// 操作数组
result = _.reject([1, 2, 3, 4], function (value) {
return value % 2 === 1;
});
console.log(result) //=> [2, 4]
// 操作对象
result = _.reject({ one: '一', two: '二', three: '三', num: 123, bool: false }, function (value) {
return typeof value === "string";
});
console.log(result) //=> [123, false]
// 操作复杂的对象
var obj = {
levelA: {
level0: 'level0',
level1: 'level1'
},
levelB: '一',
levelC: 1,
levelD: {
level3: 'level3'
}
}
result = _.reject(obj, function (value) {
return typeof value === "object";
});
console.log(result) //=> ["一", 1]
// 操作字符串(此处将字符拆分为数组)
result = _.reject('123', function (value) {
return value === '2';
});
console.log(result) //=> ["1", "3"]
//操作arguments
function abc() {
result = _.reject(arguments, function (value) {
return value % 2 === 1;
});
console.log(result); //=> [2, 4]
}
abc(1, 2, 3, 4);
var result;
//数组的情况
result = _.reject([1, 2, 3], function (value, key, list) {
console.log(value, key, list);
//=> 1 0 [1, 2, 3]
//=> 2 1 [1, 2, 3]
//=> 3 2 [1, 2, 3]
});
console.log(result) //=> [1, 2, 3]
//对象的情况
result = _.reject({one: '一', two: '二', three: '三'}, function(value, key, list){
console.log(value, key, list);
//=> 一 one Object {one: "一", two: "二", three: "三"}
//=> 二 two Object {one: "一", two: "二", three: "三"}
//=> 三 three Object {one: "一", two: "二", three: "三"}
});
console.log(result) //=> ["一", "二", "三"]
var result;
// 数组的情况
result = _.reject([1, 2, 3], function (value, key, list) {
console.log(this); //=> [1, 2, 3] this是数组
}, [1, 2, 3]);
// 对象的情况
result = _.reject([1, 2, 3], function (value, key, list) {
console.log(this); //=> Object {no: 10} this是对象
}, { "no": 10 });
// 字符串的情况
result = _.reject([1, 2, 3], function (value, key, list) {
console.log(this); //=> String {0: "1", 1: "2", 2: "3", length: 3, [[PrimitiveValue]]: "123"}
// this是将字符串拆分后的对象
}, "123");
//例如:null,undefined,0,true,this等;
var result = _.reject(null, function (value, key, list) {
return true;
});
console.log(result) //=> []
// 例如:null,undefined,window,this等
var result = _.reject([1, 2, 3], function (value, key, list) {
console.log(this); //=> this是window全局对象
}, null);
var result = _.reject([1, true, '1', 0, undefined, null]);
console.log(result) //=> [0, undefined, null]
var result = _.reject({x: 1, y: 2, z: false});
console.log(result) //=> [false]
var result = _.reject([{x: 1}, {y: 2}], 'x');
console.log(result) //=> [{y: 2}]
var obj = [
{x: 1, y: 2},
{x: 1},
{y: 2, z: 3}
]
var result = _.reject(obj, {x: 1});
console.log(result) //=> [{y: 2, z: 3}]