_.every(list, predicate, [context])
对list集合的每个成员根据predicate进行真值检测,如果都通过真值检测则返回true
var result;
// 操作数组
result = _.every([0, 10, 20], function (value) {
return value % 2 === 0;
});
console.log(result) //=> true
// 操作对象
result = _.every({ one: '一', two: '二', three: '三', four: false }, function (value) {
return typeof value === 'string';
});
console.log(result); //=> false
// 操作字符串(此处将字符拆分为数组)
result = _.every('123', function (value) {
return value !== '0' ? true : false;
});
console.log(result) //=> true
//操作arguments
function abc() {
result = _.every(arguments, function (value) {
return value % 2 === 0;
});
console.log(result); //=> true
}
abc(0, 10, 20);
// predicate为不传值(且list集合里的内容全部为真值返回true,否则返回false)
var result;
result = _.every([1, 2, 3]);
console.log(result); //=> true
//数组的情况
result = _.every([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]
return true;
});
//对象的情况
result = _.every({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: "三"}
return true;
});
var result;
// 数组的情况
result = _.every([1, 2, 3], function (value, key, list) {
console.log(this); //=> [1, 2, 3] this是数组
}, [1, 2, 3]);
// 对象的情况
result = _.every([1, 2, 3], function (value, key, list) {
console.log(this); //=> Object {no: 10} this是对象
}, { "no": 10 });
// 字符串的情况
result = _.every([1, 2, 3], function (value, key, list) {
console.log(this); //=> String {0: "1", 1: "2", 2: "3", length: 3, [[PrimitiveValue]]: "123"} this是将字符串拆分后的对象
}, "123");
var result = _.all([1, 2, 3], function (value, key, list){
return value > 1;
});
console.log(result) //=> false
var result = _.every(null);
console.log(result) //=> true 直接返回不做任何操作
// 例如:null,undefined,window,this等
var result = _.every([1, 2, 3], function (value, key, list) {
console.log(this); //=> this是window全局对象
return true;
}, null);
console.log(result) //=> true
var result = _.every([{ x: 1 }, { x: 1 }], 'x');
console.log(result) //=> true 会检测key是否全部为x
var obj = [
{ x: 1, y: 2 },
{ x: 1 },
{ x: 1, z: 3 }
]
var result = _.every(obj, { x: 1 });
console.log(result) //=> true
// _.identity方法
var result = _.every([1, 2, 3], _.identity);
console.log(result) //=> true
// _.isNumber方法
var result = _.every([1, 2, 3, 'srt'], _.isNumber);
console.log(result) //=> false
// _.isObject方法
var obj = [
{ x: 1, y: 2 },
{ x: 1 },
{ x: 1, z: 3 }
]
var result = _.every(obj, _.isObject);
console.log(result) //=> true