1. 程式人生 > >使用ES6新陣列方法(象C# Lambda表示式一樣寫查詢語句)

使用ES6新陣列方法(象C# Lambda表示式一樣寫查詢語句)

let people = [
    {id: 1, name: "a", age: 12}, 
    {id: 2, name: "b", age: 13}, 
    {id: 3, name: "c", age: 14}, 
    {id: 4, name: "d", age: 15}, 
    {id: 5, name: "e", age: 16}
];

const kids = [];
people.forEach(person => {
    if (person.age < 15) {
        kids.push({
            id: person.id,
            name: person.name
        })
    }
});
console.log(kids);

//map & filter都是陣列的方法!
//返回項參與的表示式值
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(number => number * 2); //[2,4,6,8,10]
console.log(doubled);

//返回滿足條件的項
const even = numbers.filter(number => number % 2 === 0); //[2,4]
console.log(even);

//把用forEach示例重寫
const kids2 = people
    .filter(person => person.age < 15)
    .map(person => ({
        id: person.id,
        name: person.name
    }));
console.log(kids2);

/*
結論:從上面的示例可知,filter相當於C#的where過濾條件,map相當於C#的select投影
*/