javascript - ES6サンプル

概要

ES6のサンプルコード。

サンプルコード

forEach

var cars = [
    { no: 1, "price": 100 },
    { no: 2, "price": 200 },
    { no: 3, "price": 300 },
    { no: 4, "price": 400 },
]

cars.forEach(x => {
    console.log(x)
});

map

var dcars = cars.map(x => {

    return {
        no: x.no += 10,
        x : x.price * 3,
    }
});

console.log(dcars)

filter

var fcars =cars.filter(x => {
    return (x.no % 2) === 0;
});

console.log(fcars)

function getProduct(id){
    return cars.filter(x => {
        console.log(x.no)
        return x.no === id
    })
}

console.log(getProduct(12))

find

const animals = [
    { 'id': 1, 'category': 'animal', 'kind': 'dog' },
    { 'id': 2, 'category': 'animal', 'kind': 'cat' },
    { 'id': 3, 'category': 'animal', 'kind': 'bird' },
    { 'id': 4, 'category': 'animal', 'kind': 'fish' },
    { 'id': 5, 'category': 'animal', 'kind': 'human' },
]

var dogs = animals.find(x => {
    return x.category === 'animal' && x.kind === 'human';
})

console.log(dogs)

every

const computers = [
    { name: "apple", ram: 24 },
    { name: "dell", ram: 32 },
    { name: "ms", ram: 64 },
]

var result = computers.every(x => {
    return x.ram >= 24;
});

console.log(result)

some

var result = computers.some(x => {
    return x.ram >= 32;
});

console.log(result)

reduce

var numbers = [1,2,3,4]
var sumResult = numbers.reduce((sum, number) => {
    return sum + number;
}, 0);

console.log("sum:" + sumResult);

var colors = ["red","yellow", "blue"]
var addColors = colors.reduce((x, color) => {
    x.push(color);
    return x;
}, []);

console.log(addColors)

テンプレートリテラル

let nowYear = 2020
console.log(`year:${nowYear}`)

アロー関数

const add = (x, y) => {
     return x + y;
}

// 一行にもできる
const add = (x, y) => x + y;

console.log(add(1, 2))

オブジェクトリテラル

function createBookStore(inventory) {
    return {
        inventory,
        inventoryValue() {
            return this.inventory.reduce((total, book) => {
                return total + book.price;
            }, 0);
        },
        priceForTitle(title) {
            return this.inventory.find(book => {
                return book.title === title;
            }).price;
        }
    };
}

const inventory = [
    { title: "harry", price: 1000 },
    { title: "js", price: 2000 },
]

store = createBookStore(inventory);
console.log(store.inventoryValue())
console.log(store.priceForTitle("js"))

デフォルト引数

function createMake(url, method='GET'){
    console.log(method)
}

createMake("google.com")
createMake("google.com", "POST")

Rest演算子

function addNumbers(...numbers) {
    // 配列に変換
    return numbers.reduce((sum, number) => {
        return sum + number;
    }, 0)
}

console.log(addNumbers(1, 2, 3, 4))

Spread演算子

const defaultColors = ["red", "blue", "yellow"]
const customColors = ["orange", "green"]
// 配列を展開
const myColors = ["black", ...defaultColors, ...customColors];
console.log(myColors)

分割代入

分割代入

var expense = {
    type: "pc",
    kakaku: "4000"
}

const {type, kakaku} = expense
console.log(type)
console.log(kakaku)

const { type:myType, kakaku:myKakaku } = expense
console.log(myType)
console.log(myKakaku)

分割代入 - 関数の引数

function test({ type, kakaku }){
    console.log(`${type} => ${kakaku}`)
}

test(expense)

分割代入 - 配列

const points = [
    [4,5],
    [11,1],
    [0,40]
]

console.log(
    points.map(([x, y]) => {
        return { x: x, y: y}
    })
);

クラス

class Car {
    constructor({ title }){
        this.title = title;
    }

    drive() {
        return "buruburu!";
    }
}

class Honda extends Car {
    constructor(options){
        super(options);
        this.color = options.color;
    }

    honk() {
        return "bubu!!!";
    }

}

const honda = new Honda({title:'puri',color:'red'});
console.log(`${honda.title} - ${honda.color}`);
console.log(honda.drive())

ジェネレーター

generator - basic

function* colors(){
    yield  'read',
    yield  'blue',
    yield  'green'
}

const myCols = [];
for (const color of colors) {
    myCols.push(color)
}
console.log(myCols)

generator - Symbol.iterator

const teamPush = {
    lead: "kotaki",
    tester: "mukai",
    [Symbol.iterator]: function* () {
        yield this.lead;
        yield this.tester;
    }
}

const teamStack = {
    teamPush,
    name:"dev",
    lead:"sato",
    manager:"nakai",
    engineer: "hirakawa",
    [Symbol.iterator]: function* () {
        yield this.lead;
        yield this.manager;
        yield this.engineer
        yield* this.teamPush;
    }
}

for (const member of teamStack) {
    console.log(member)
}

generator - 再帰処理

class Comment {
    constructor(content, children) {
        this.content = content;
        this.children = children;
    }

    *[Symbol.iterator]() {
        yield this.content;
        for (const child of this.children) {
            yield* child;
        }
    }
}

const children = [
    new Comment("yes", []),
    new Comment("no", []),
    new Comment("mugon...", [])
]

const tree = new Comment("good news", children)

const values = [] 
for (const content of tree) {
    values.push(content);
}

console.log(values)

Promise

Promise - basic

let pflag = true;

let promise = new Promise((resolve, reject) => {
    console.log("exe promise.");
    if (pflag) {
        resolve();
    } else {
        reject();
    }
});

promise
    .then(() => {
        console.log("then_1")
    })
    .then(() => {
        console.log("then_2")
    })
    .catch(() => {
        console.log("catch_1")
    });

Promise - fetch

const fetch = require('node-fetch');

let url = "https://api.github.com/users/github"

fetch(url)
    .then(res => {
        console.log(res.status)
        return res.json();
    })
    .then(json => {
        console.log(json)
    })
    .catch(error => {
        // リクエストが失敗した場合はcatchが実行される
        // サーバーがレスポンスを返した場合は、catchは処理されずにthenが実行される
        console.log("error!"); //
        console.log(error);
    });

async/await

Promiseオブジェクトをイメージ。
const axios = require('axios');

async function asyncFunc() {
    const res1 = await axios.get('https://api.github.com/users/github');
    console.log("1st")
    const res2 = await axios.get('https://api.github.com/users/github');
    console.log("2nd")
    console.log(res1.data.id + "," + res2.data.id);
}

asyncFunc();
結果の処理順
1st
2nd
9919,9919