需求:想要让对象也是用例如 map() filter()等方法
使用underscore库:
-
下载underscore包:
npm i underscore
-
引入:
<script src="./node_modules/underscore/underscore-min.js"></script>
或
require(underscore)
-
使用:
使用_
前缀调用,返回一个数组
例:
let arr = _.map({ a: 1, b: 2, c: 3 },(v,k) => k + '=' + v)
console.log(arr) // ["a=1", "b=2", "c=3"]
-
方法:
map / filter
传入的函数是function(value,key) `第一个参数是value 第二个参数是key`
let obj = { name: 'bob', school: 'No.1 middle school', address: 'xueyuan road' } //返回数组 let upper = _.map(obj, function (value, key) { return `${key}:${value}`; }); console.log(upper) // [name:bob,school:No.1 middle school,address:xueyuan road] //返回对象 let upperObj = _.mapObject(obj, function (value, key) { return `${key}:${value}`; }); console.log(upperObj) //{ // name:"name:bob", // school:"school:No.1 middle school", // address:"address:xueyuan road" //}
every / some
所有元素都满足条件时 `_.every()` 返回`true` 至少一个元素满足条件时,`_.some()`返回`true`
let res = _.every({ a: 1, b: 2, c: 3 }, (v, k) => v > 2) //false let res1 = _.some({ a: 1, b: 2, c: 3 }, (v, k) => v > 2) //true
max / min
只作用于`value`,忽略`key`
_.max({ a: 1, b: 2, c: 3 }) //3
groupBy
`groupBy()`把集合的元素按照key归类,key由传入的函数返回
let scores = [20, 81, 75, 40, 91, 59, 77, 66, 72, 88, 99] let groups = _.groupBy(scores,function(x){ if(x < 60){ return 'C' }else if(x < 80){ return 'B' }else{ return 'A' } }) /* result: { A:[81, 91, 88, 99], B:[75, 77, 66, 72], C:[20, 40, 59] } */
shuffle / sample
shuffle()
用洗牌算法随机打乱一个集合//每次结果都不一样 _.shuffle([1,2,3,4,5,6]) //[3,5,6,2,4,1]
sample()
随机选择一个或多个元素//每次结果度不一样 //随机选一个 _.sample([1,2,3,4,5,6]) //3 //随机选三个 _.sample([1,2,3,4,5,6]) //[2,5,1]
[文档自查][https://underscorejs.org/#collections]
文中仅列出array的一些方法,还有很多方法,可以查看上链接