分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

underscorejs之_.countBy(list, iteratee, [context])

发布时间:2023-09-06 01:15责任编辑:董明明关键词:js

语法

_.countBy(list, iteratee, [context])

说明

排序一个列表组成一个组,并且返回各组中的对象的数量的计数。类似groupBy,但是不是返回列表的值,而是返回在该组中值的数目。就像EXCEL里的分类统计

  • list为 遍历的集合,如数组、对象、字符串、arguments等。
  • iteratee 迭代器,可以是一个function也可以字符串等。
  • iteratee 有三个参数 (element, index, list)
  • iteratee 需要有返回
  • context 执行上下文,改成iteratee内的this

代码示例

示例一:根据iteratee分类统计

var parity = _.countBy([1, 2, 3, 4, 5], function (num) { ???return num % 2 === 0;});//符合条件的key为在true,不符合条件的key为false。console.log(parity); //=> Object {false: 3, true: 2}

示例二:返回结果的Object指定key

var parity = _.countBy([1, 2, 3, 4, 5], function(num) { ?return num % 2 == 0 ? ‘even‘: ‘odd‘;});console.log(parity); //=> Object {odd: 3, even: 2}

示例三:改变iteratee内的this

var parity = _.countBy(‘12345‘, function (num) { ???console.log(this); //5 times => Object {no: 3} ???return num > this.no;}, {no : 3});console.log(parity); //=> Object {false: 3, true: 2}

示例四:iteratee的三个参数& 不要忘记return

var parity = _.countBy(‘abc‘, function (element, index, list) { ???console.log(element, index, list); ???//=> a 0 abc ???//=> b 1 abc ???//=> c 2 abc});console.log(parity); //=> Object {undefined: 3}

iteratee可以是对象的属性

var list = [‘one‘, ‘two‘, ‘three‘, ‘four‘, ‘five‘, ‘six‘, ‘seven‘, ‘eight‘, ‘nine‘, ‘ten‘];var grouped = _.countBy(list, ‘length‘);console.log(grouped); //=> Object {3: 4, 4: 3, 5: 3}

iteratee可以是对象的key

var list = [{x:‘a‘}, {x:‘b‘}, {x:‘a‘}];var grouped = _.countBy(list, ‘x‘);console.log(grouped); //=> Object {a: 2, b: 1}

iteratee可以是对象

var list = [{x:0, y:0}, {x:0, y:1}, {x:1, y:1}];var grouped = _.countBy(list, {x:0});console.log(grouped); //=> Object {true: 2, false: 1}

不传iteratee则以值进行分类统计

var parity = _.countBy(‘abcab‘);console.log(parity); //=> Object {a: 2, b: 2, c: 1}

非集合返回{}

console.log(_.countBy(0)); //=> Object {}console.log(_.countBy(NaN)); //=> Object {}console.log(_.countBy(null)); //=> Object {}console.log(_.countBy(undefined)); //=> Object {}console.log(_.countBy(true)); //=> Object {}console.log(_.countBy(false)); //=> Object {}

underscorejs之_.countBy(list, iteratee, [context])

原文地址:http://www.cnblogs.com/rechel/p/7615199.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved