Lodash:JavaScript插件

1 Vue引入

  1.1 添加依赖

 "dependencies": {
    "vue": "^2.5.2",
    "vue-router": "^3.0.1",
    "vuex": "^3.4.0",
    "lodash": "^4.17.11"
  }

  1.2 main.js配置全局

import _ from "lodash";
Vue.prototype._ = _

1.3 组件引入

import _ from "lodash";

2 常用方法介绍

2.1 Array用法

compact:中文意思是“紧凑的”,去假

//-1,0,1,false,2,3
_.compact([-1, 0, "0", 1, false, "false", 2, '', 3])

remove:搬除,原数组中满足判断条件的值,返回一个搬除数组,当然原来的数组也变化了,元素被搬走了 

 var array = [1, 2, 3, 4];
 var evens = _.remove(array, function (n) {
        return n % 2 == 0;
  });
  console.log(array);// => [1, 3]
  console.log(evens);// => [2, 4]

join:拼接,按一定符号拼接数组为字符串
slice:数组array,从 start 位置开始到end结束,但不包括 end 本身 

//a~b~
console.log(_.join(['a', 'b', ''], '~'));

//["a", "b"]
console.log(_.slice(['a', 'b', 'c'], 0, 2))

 shift:删除并返回数组的第一个元素
 unshift向数组的开头添加一个或多个元素,并返回长度

// a
console.log(['a', 'b', 'c'].shift());

// 6
console.log(['a', 'b', 'c'].unshift("1", "2", "3"));

uniq创建一个去重后的array数组副本
uniqBy 

//-1,0,0,1,false,false,2,,3,6,66,666
_.uniq([-1, 0, "0", "0", 1, false, "false", 2, '', 3, 6, 66, 666, 6])

//[{ 'x': 2 }, { 'x': 3,'y':2 }]
_.uniqBy([{ 'x': 2 }, { 'x': 3,'y':2 },{ 'x': 3 }], 'x')

 xorBy:两个数组对象去重

var arr = _.xorBy(
          [{ name:'cai',age:12 }, { name:'ccc',age:18}, { name:'ddd',age:18}],
          [{ name:'cai',age:14 }, { name:'bbb',age:18}],
          'age'
        );
//[{ name:'cai',age:12 },{ name:'cai',age:14}]
 console.log(arr)

differenceBy:数组对象去重,从第一个数组中删除与第二个数组中'age'值相同的对象(与xorBy的不同) 
differenceWith:跟differenceBy方式类似,但是第三个参数为比较器 

let newArr =_.differenceBy(
          [{ name:'cai',age:12 }, { name:'ccc',age:18}, { name:'ddd',age:18}],
          [{ name:'cai',age:14 }, { name:'bbb',age:18}],
          'age'
        );
//[{ name:'cai',age:12 }]
console.log(newArr)


 var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
 newArr = _.differenceWith(objects, [{ 'x': 2, 'y': 1 }], _.isEqual);
//[{ 'x': 1, 'y': 2 }]
 console.log(newArr)

drop:数组删除前面参数 drop(array, [n=1]) 

console.log(_.drop([1, 2, 3]));//[2, 3]
console.log(_.drop([1, 2, 3], 2));//[3]
console.log(_.drop([1, 2, 3], 5));//[]
console.log(_.drop([1, 2, 3], 0));//[1,2,3]

intersection:多个数组求交集 

intersectionBy:这个方法类似_.intersection,区别是它接受一个 iteratee 调用每一个arrays的每个值以产生一个值,通过产生的值进行了比较。结果值是从第一数组中选择。

var arr=[1,2,3,4,5,6]
var arr1=[1,2,3,5,7,9]
var arr2=[1,2,4,5,7,9]
//[1,2,5]
console.log(_.intersection(arr,arr1,arr2));
 var arr = [{ name:'cai',age:12 }, { name:'bbb',age:18}, { name:'ddd',age:18}];
 var arr1 = [{ name:'cai',age:14 }, { name:'bbb',age:18}];
//[{ name:'cai',age:12 }, { name:'bbb',age:18}]
 console.log(_.intersectionBy(arr,arr1,'age'));



//区别是它接受一个 iteratee 调用每一个arrays的每个值以产生一个值,通过产生的值进行了比较
_.intersectionBy([2.1, 1.2], [4.3, 2.4], Math.floor);
// => [2.1]
//Math.floor 向上取整
 
// The `_.property` iteratee shorthand.
_.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
// => [{ 'x': 1 }]

pull:删除数组中值相同的项,pull(array, [values])
pullAllBy:删除数组对象中指定属性相同的项
pullAt:删除数组中的某一项 

 var array = [1, 2, 3, 1, 2, 3];
//[1,1] 会改变原数组,返回值就是原数组
 console.log(_.pull(array, 2, 3));

 array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
//[{x: 2}]
 console.log( _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'));

  array = [5, 10, 15, 20];
  var evens = _.pullAt(array, 1, 3);
  console.log(array);    // => [5, 15]
  console.log(evens);    // => [10, 20]

 

2.2 Collection用法

forEach:

_([1, 2]).forEach(function (value) {
          console.log(value);// => Logs `1` then `2`.
        });


        _.forEach({'a': 1, 'b': 2}, function (value, key) {
          console.log(key + "===" + value);// => Logs 'a' then 'b' (iteration order is not guaranteed).
        });

map: 

    function square(n) {
          return n * n;
    }

     console.log(_.map([4, 8], square));// => [16, 64]
     console.log(_.map(['  foo  ', '  bar  '], _.trim));// => ['foo', 'bar']

filter: 

 var users = [
          {'user': 'barney', 'age': 36, 'active': true},
          {'user': 'fred', 'age': 40, 'active': false}
 ];
//[{'user': 'fred', 'age': 40, 'active': false}]
 console.log(_.filter(users, function (o) {
          return !o.active;
 }));// => objects for ['fred']

//[{'user': 'barney', 'age': 36, 'active': true}]
 console.log(_.filter(users, 'active'));// => objects for ['barney']

reject: 返回非真值,是_filter的反向方法 

   var users = [
          {'user': 'barney', 'age': 36, 'active': true},
          {'user': 'fred', 'age': 40, 'active': false}
        ];

        //[{'user': 'barney', 'age': 36, 'active': true}]
        console.log(_.reject(users, function (o) {
          return !o.active;
        }));
       // [{'user': 'fred', 'age': 40, 'active': false}]
        console.log(_.reject(users, 'active'));

这里区分注意一下,filter和reject断言之后都是返回新数组,不改变老数组,而remove断言之后是改变老数组的。 

sortBy:创建一个元素数组。 以 iteratee 处理的结果升序排序

     var users1 = [
          {'user': 'fred', 'age': 48},
          {'user': 'barney', 'age': 36},
          {'user': 'fred', 'age': 40},
          {'user': 'barney', 'age': 34}
        ];
    // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]    
console.log(_.sortBy(users1, function (o) {
          return o.user;
        }));
   // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]     
console.log(_.sortBy(users1, ['user', 'age']));

includes:_.includes(collection, value,[fromIndex=0]),检查 value(值) 是否在 collection(集合) 中。如果 collection(集合)是一个字符串,那么检查 value(值,子字符串) 是否在字符串中,否则使用做等值比较。如果指定 fromIndex 是负数,那么从 collection(集合) 的结尾开始检索 

 console.log(_.includes([1, 2, 3], 1));// => true
 console.log(_.includes([1, 2, 3], 1, 2));// => false
 console.log(_.includes({'user': 'fred', 'age': 40}, 'user'));// => true
 console.log(_.includes('pebbles', 'eb'));// => true

size:返回collection(集合)的长度,如果集合是类数组或字符串,返回其 length ;如果集合是对象,返回其可枚举属性的个数 

console.log(_.size([1, 2, 3])); // => 3
console.log(_.size({'a': 1, 'b': 2})); // => 2
console.log(_.size('pebbles')); // => 7

2.3 Object用法

forIn:_.forIn(object,[iteratee=_.identity]),遍历函数会传入3个参数:(value, key,object);forEach更多的用做集合,而forIn用做对象: 

function Foo() {
          this.a = 1;
          this.b = 2;
        }
 Foo.prototype.c = 3;
 _.forIn(new Foo, function (value, key) {
        console.log(key + ":" + value);
 });// => Logs 'a', 'b', then 'c' (无法保证遍历的顺序)。

assignIn:合并对象 

function Foo() {
          this.a = 1;
          this.b = 2;
        }
Foo.prototype.c = 3;   
function Bar() {
          this.c = 3;
        }
 Foo.prototype.e = 7;
 Bar.prototype.d = 4;

// => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
 console.log(_.assignIn({ 'a': 0 }, new Foo, new Bar));

get:  _.get(object,path,[defaultValue])
set:  _.set(object,path,[defaultValue])

var object = { 'a': [{ 'b': { 'c': 3 } }] };
 console.log(_.get(object, 'a[0].b.c')); // => 3

var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.set(object, 'a[0].b.c', 4);
console.log(object.a[0].b.c); // => 4

values:_.values(object),把object本身属性的值返回为数组。
 

function Foo() {
          this.a = 1;
          this.b = 2;
}
Foo.prototype.c = 3;
console.log(_.values(new Foo)); // => [1, 2] (无法保证遍历的顺序)
console.log(_.values('hi'));//["h","i"]

once:只有第一次会调用,多次调用返回第一次的结果: 

 function tt1(num){
          console.log("tt1="+num);//只进第一次
          return num;
}
 var initialize = _.once(tt1);


  console.log(initialize(1));// 1
  console.log(initialize(2));// 1

delay:延迟。 

  _.delay(function(text) {
          console.log(text);
  }, 3000, 'later');// => 3秒后输出 'later'。

2.4 String用法

trim:去空格,或者去固定符号。

console.log(_.trim('  abc  '));//abc
console.log(_.trim('-_-abc-_-', '_-'));//abc
console.log(_.map(['  foo  ', '  bar  '], _.trim));//["foo", "bar"]

2.5 Math用法

console.log(_.add(6, 4));//10
console.log(_.subtract(6, 4));//2
console.log(_.divide(6, 4));//1.5
console.log(_.min([4, 2, 8, 6]));//2
console.log(_.min([]));//undefined


console.log(_.max([4, 2, 8, 6]));//8
console.log(_.max([]));//undefined

console.log(_.sum([4, 2, 8, 6]));//20
console.log(_.round(4.006));//4
console.log(_.round(4.546));//5
console.log(_.round(4.906));//5



console.log( _.random(0, 5));// => an integer between 0 and 5
console.log(_.random(5));// => also an integer between 0 and 5
console.log(_.random(5, true));// => a floating-point number between 0 and 5
console.log(_.random(1.2, 5.2));// => a floating-point number between 1.2 and 5.2

2.6 Date用法

console.log(_.now());

//获得 Unix 纪元 (1 January 1970 00:00:00 UTC) 直到现在的毫秒数。
_.defer(function(stamp) {
      console.log(_.now() - stamp);
}, _.now());// => 记录延迟函数调用的毫秒数

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值