1,every循环数组是只有当数组中的所有元素都满足条件时every() 才返回 true;或者可以这样说只要有一个不满足条件则返回false
function fun (value, index, ar) {
if (value % 2 == 0) {
return true;
}else {
return false;
}
}
var a = [4,2,7,10,8];
if (a.every(fun)) {
console.log("都是偶数");
}else{
console.log("不都是偶数");
}
2,some只要数组中只要有一个元素满足条件,some() 就返回 true,所有的都不满足条件则返回false
function fun (value, index, ar) {
if (value % 2 == 0) {
return true;
}else {
return false;
}
}
var a = [4,2,7,10,8];
if (a.some(fun)) {
console.log("不都是偶数");
}else{
console.log("都不是偶数");
}
//不全为偶数
3,some和every的另一个参数的用法 (callbackfn[, thisArg]),可选参数,可在 callbackfn 函数中为其引用 this 关键字的对象。如果省略 thisArg,则 undefined 将用作 this 值。
var f = function (value) {
if (typrof value !== 'number') {
return false;
}else {
return value >=this.min && value <= this.max;
}
var a = [10,15,19];
var obj = {min : 10, max : 20};
if (a.every(f, obj)) {
console.log("都在指定范围内。");
} else {
console.log("部分不在范围内。");
}