1._.forEach(collection, [iteratee=_.identity], [thisArg]) 遍历
_.forEach([22,33,11,55],function (value) {//若一个参数,返回的便是其value值 console.log(value);//22 33 11 55 }); _.forEach([22,33,11,55],function (value,index) {//这里规定的就是第一个参数返回的是value值,第二个参数是下标index console.log(value); });
2._.sortBy(collection, [iteratee=_.identity], [thisArg]) 排序匿名函数+字符串
var arr = [ {name: 'bb',age:23},
{name: 'aa',age:22} ]; var arrSortResult = _.sortBy(arr, function(item){ return item.name; }); _.forEach(arrSortResult, function(item){ console.log(item.name); //aa bb });
var strSortResult = _.sortBy('cda').join('');//join()方法 方法用于把数组中的所有元素放入一个字符串。元素是通过指定的分隔符进行分隔的。 console.log(strSortResult);//acd
3._.sortedIndex(array, value, [iteratee=_.identity], [thisArg])
参数:array (Array): 需要检查的数组 value (*): 插入的判断参数 [iteratee=_.identity](Function|Object|string): 遍历方法 [thisArg] (*): iteratee的绑定值
var collection = ['a', 'b', 'c', 'd', 'f']; console.log('before: ' + collection.join(' '));//before: a b c d f var toBeInserted = 'e'; var sortedIndex = _.sortedIndex(collection, toBeInserted); console.log("This is sortedIndex:"+sortedIndex);//This is sortedIndex:4 collection.splice(sortedIndex, 0, toBeInserted); console.log('after:' + collection.join(' '));//after:a b c d e f

本文介绍 Lodash 库中 _.forEach 和 _.sortBy 方法的使用技巧,包括基本用法、参数详解及示例代码。通过匿名函数实现数组元素的遍历与基于特定属性的排序。
869

被折叠的 条评论
为什么被折叠?



