Lodash.js测试,数组(Array.prototype)方法的扩展

版权声明:本文为个人知识整理,欢迎指正、交流、转载。 https://blog.csdn.net/u014711094/article/details/83151048

1 Util

  • property propertyOf
let o = {a: {b: {c: 3}}}

// string形式较为明确、灵活
_.property('a.b.c')(o)			// 3, recommendation
_.property(['a', 'b', 'c'])(o)	// 3

// the opposite of property
_.propertyOf(o)('a.b.c')	// 3
_.propertyOf(o)(['a', 'b', 'c'])	// 3

// 注意下面的写法
_.property('a[b].c')(o)			// 3
_.property(['a', 'b.c'])(o)		// undefined

let o = {a: [1, {b: 2}]}
_.property('a[1].b')(o)			// 2, recommendation
_.property('a.1.b')(o)			// 2
_.property(['a', '1', 'b'])(o)	// 2
  • matchesProperty matches
let objs = {a: {b: 2, c: 3}}

// 深度比较(deep comparation)
_.matchesProperty('a', {b: 2})(o)		// true
_.matches({b: 2})(o.a)					// true
  • property propertyOf matchesProperty matches用法示例
let objs = [{a: 1}, {a: 2, b: 2}, {a: 3}]

_.map(objs, _.property('a'))	// [1, 2, 3]
_.map(objs, 'a')				// 简写

_.reject(objs, _.matchesProperty('a', {b: 2}))	// [{a: 1}, {a: 3}]
_.reject(objs, ['a', {b: 2}])					// 简写
_.reject(objs, ['a.b', 2])						// 简写

_.reject(objs, _.matches({b: 2}))		// [{a: 1}, {a: 3}]
_.reject(objs, {b: 2})					// 简写

2 Collection

  • map forEach forEachRight
let o = {a: 1, b: 2, c: 3}

// lodash将Arrry的部分方法extend到Object, 返回包含val的Array
// Object: (val, key, obj)相当于Array: (val, idx, arr)
_.map(o, (v, k, o) => k + v)		// ['a1', 'b2', 'c3']

// each eachRight分别是forEach forEachRight的别名
// 输出: a1 b2
_.forEach(o, (v, k, o) => {
  console.log(k + v)
  return v < 2	// 停止遍历, 和Array.prototype.forEach不同
})
  • some every filter reject find findLast
let o = {a: 1, b: 2, c: 3}

_.every(o, v => v > 2)		// false
_.some(o, v => v > 2)		// true

_.filter(o, v => v > 2)		// [3]
_.reject(o, v => v > 2)		// [1, 2]

_.find(o, v => v > 1)		// 2
_.findLast(o, v => v > 1)	// 3

let users = {
  'barney':  { 'age': 36, 'active': true },
  'fred':    { 'age': 40, 'active': false },
  'pebbles': { 'age': 32, 'active': true }
}

// 原Arrry.prototype上的方法, 返回Array
// 回调的arguments是(val, key, obj)
_.every(users, 'active')	// false
_.some(users, 'active')		// true

_.filter(users, ['age', 40])	// [{'age': 40, 'active': false}]
_.filter(users, {'age': 40})	// [{'age': 40, 'active': false}]
_.reject(users, 'active')		// [{'age': 40, 'active': false}]

_.find(users, 'active')			// {'age': 36, 'active': true}
_.findLast(users, 'active')		// {'age': 32, 'active': true}

3 Object

  • findKey findLastKey mapKeys mapValues
let o = {a: 1, b: 2, c: 3}

// lodash为Object提供类似于Array的方法, 回调的参数是(val, key, obj)
// Object: (val, key, obj)相当于Array: (val, idx, arr)
_.findKey(o, v => v > 1)		// 'b'
_.findLastKey(o, v => v > 1)	// 'c'

_.mapKeys(o, (v, k) => k + v)	// {a1: 1, b2: 2, c3: 3}
_.mapValues(o, v => v + 1)		// {a: 2, b: 3, c: 4}

猜你喜欢

转载自blog.csdn.net/u014711094/article/details/83151048