How to write the Array.prototype.every() method in Javascript -
as practice, want write function all() works similar array.prototype.every() method. function returns true if predicate supplied returns true items in array.
array.prototype.all = function (p) { this.foreach(function (elem) { if (!p(elem)) return false; }); return true; }; function isgreaterthanzero (num) { return num > 0; } console.log([-1, 0, 2].all(isgreaterthanzero)); // should return false because -1 , 0 not greater 0
somehow doesn't work , returns true
. what's wrong code? there better way write this?
you can't break out of array#foreach loop returning. use loop instead.
note: partial implementation of array#every demonstrate return issue.
array.prototype.all = function (p) { for(var = 0; < this.length; i++) { if(!p(this[i])) { return false; } } return true; }; function isgreaterthanzero (num) { return num > 0; } console.log([-1, 0, 2].all(isgreaterthanzero));
Comments
Post a Comment