码迷,mamicode.com
首页 > 编程语言 > 详细

[Javascript] Lodash: Refactoring Simple For Loops (_.find, _.findLast, _.filter)

时间:2015-03-21 22:48:57      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:

This lesson shows how to refactor your old loops into using a simpler and more powerful lodash-style. We will start by looking at how many people traditionally write JavaScript for loops and then talk about the alternate style and benefits that Lodash offers.

 

If you want to find one value from the value, you can use:

_.find 

or 

_.findLast

 

If you want to get all match results, you can use:

_.filter()

 

var people = [
    {name: "Frank", age: 30, gender: ‘male‘},
    {name: "Bill", age: 22, gender: ‘male‘},
    {name: "Carol", age: 52, gender: ‘female‘},
    {name: "Susan", age: 10, gender: ‘female‘},
    {name: "Stephanie", age: 22, gender: ‘female‘},
    {name: "Kyle", age: 68, gender: ‘male‘},
    {name: "Hank", age: 22, gender: ‘male‘},
    {name: "Susan", age: 20, gender: ‘female‘}
];

//Loop: find one ‘Susan‘
var susan;
for (var i = 0; i < people.length; i++) {
    var person = people[i];
    if(person.name == "Susan"){
        susan = person;
        break;
    }
}

console.log(susan);

//Lodash: find one ‘Susan‘
var susan2 = _.find(people, {name: ‘Susan‘});

console.log(susan2);


//Loop: find all ‘Susan‘
var susans = [];
for (var i = 0; i < people.length; i++) {
    var person = people[i];
    if(person.name == "Susan"){
        susans.push(person);
    }
}

console.log(susans);

//Lodash: find all ‘Susan‘
var susans2 = _.filter(people, {name: ‘Susan‘});

console.log(susans2);

 

[Javascript] Lodash: Refactoring Simple For Loops (_.find, _.findLast, _.filter)

标签:

原文地址:http://www.cnblogs.com/Answer1215/p/4356420.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!