underscore.js _.every()和_.some()没有回调

时间:2015-09-10 21:03:16

标签: javascript underscore.js

对于作业,我正在努力重新创建下划线的_.every()和_.some()函数来传递一组规范。但是,我无法让函数在没有回调函数的情况下工作。这是规范(两个函数的规格相同):

 it('should work when no callback is provided', function() { 
 expect(_.some([true, true, true])).to.be.true; 
 expect(_.some([true, true, false])).to.be.true; 
 expect(_.some([false, false, false])).to.be.false; 
}

以下是代码:

// Determine whether all of the elements match a truth test. 
197   _.every = function(collection, iterator) { 
198     return _.reduce(collection, function(trueCheck, item) { 
199       if (!trueCheck) {return false;} 
200       if (item === true || iterator(item)){ 
201         return true; 
202       } 
203       else return false; 
204     }, true); 
205   }; 
206 

207   // Determine whether any of the elements pass a truth test. If no iterator is 
208   // provided, provide a default one 
209   _.some = function(collection, iterator) { 
210     var isAllFalse = _.every(collection, function(item) { 
211       return !iterator(item); 
212     }); 
213     if (isAllFalse === true) { 
214       return false; 
215     } 
216     return true; 
217   }; 
218 

非常感谢任何建议,谢谢!

1 个答案:

答案 0 :(得分:0)

我会使用普通的Javascript:



var _ = _ || {};

_.every = function(collection, iterator) {
  for (var i = collection.length - 1; i >= 0; i--) {
    if (!collection[i]) return false;
  }
  return true;
};

_.some = function(collection, iterator) {
  for (var i = collection.length - 1; i >= 0; i--) {
    if (collection[i]) return true;
  }
  return false;
};

console.log(_.every([true, 'is', 1])); //true
console.log(_.every([true, 'is', false])); //false
console.log(_.some([null, '', 0, false])); //false
console.log(_.some([true, 'is', false])); //true