[1, 2, 3].all(isGreaterThanZero) => true
[-1, 0, 2].all(isGreaterThanZero) => false
[-1, 2, 3].none(isLessThanZero) => false
[-1, -2, -3].none(isGreaterThanZero) => true
[-1, 2, 3].any(isGreaterThanZero) => true
[-1, -2, -3].any(isGreaterThanZero) => false
Array.prototype.all = function (p) {
for(i = 0; i < this.length; i++) {
if(p(this[i]) !== true) {
return false;
}
}
return true;
};
Array.prototype.none = function (p) {
for(i = 0; i < this.length; i++) {
if(p(this[i]) !== false) {
return false;
}
}
return true;
};
Array.prototype.any = function (p) {
for(i = 0; i < this.length; i++) {
if(p(this[i]) !== false) {
return true;
}
}
return false;
};
测试用例
function isGreaterThanZero (num) {
return num > 0;
}
function isLessThanZero (num) {
return num < 0;
}
Test.expect([1, 2, 3].all(isGreaterThanZero), 'All are greater than zero');
Test.expect(![-1, 0, 2].all(isGreaterThanZero), 'One is less than zero');
Test.expect(![-1, 2, 3].none(isLessThanZero), 'One is less than zero');
Test.expect([-1, -2, -3].none(isGreaterThanZero), 'None are greater than zero');
Test.expect([-1, 2, 3].any(isGreaterThanZero), 'Two are greater than zero');
Test.expect(![-1, -2, -3].any(isGreaterThanZero), 'None are greater than zero');