首页 > 编程语言 > 详细

JavaScript算法题(二) && 数组filter使用

时间:2015-04-29 18:50:41      阅读:259      评论:0      收藏:0      [点我收藏+]

1.Let‘s implement the reject() function...

例: 

var odds = reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [1, 3, 5]

soluction:

function reject(array, iterator) {
    return array.filter(function(x){return !iterator(x)})
}

2.The numberOfOccurrences function must return the number of occurrences of an element in an array.

例:

var arr = [0,1,2,2,3];
arr.numberOfOccurrences(0) === 1;
arr.numberOfOccurrences(4) === 0;
arr.numberOfOccurrences(2) === 2;
arr.numberOfOccurrences("a") === 0;

soluction:

Array.prototype.numberOfOccurrences = function() {
  return this.filter( function(num){ return search === num } ).length;
}

 

JavaScript算法题(二) && 数组filter使用

原文:http://www.cnblogs.com/showtime813/p/4466398.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!