javescript經驗文檔(es6/es2017篇)

迭代器 - Iterators

{
    'use strict'
    function chef(foods){
        let i = 0;
        return {
            next(){
                let done = (i >= foods.length);
                let value = !done ? foods[i++]:undefined;

                return{
                    value:value,
                    done:done
                }
            }
        }
    }
    let wanghao = chef(['西紅柿','孫雙雙']);
    console.log(wanghao.next());
    console.log(wanghao.next());
    console.log(wanghao.next());
}

結果:
{value: "西紅柿", done: false}
{value: "孫雙雙", done: false}
{value: undefined, done: true}es6

生成器 - Generators

{
    'use strict'
    function* chef(){
        yield '西紅柿';
        yield '炒蛋';
    }
    let wanghao = chef();
    console.log(wanghao.next());
    console.log(wanghao.next());
    console.log(wanghao.next());
}

結果:
{value: "西紅柿", done: false}
{value: "孫雙雙", done: false}
{value: undefined, done: true}函數

模版字符串 - ``

{
    // 普通字符串
    let str = `In JavaScript '\n' is a line-feed.`;
    console.log(str);
     
    // 多行字符串
    let str2 = `In JavaScript this is
        not legal.`;
    console.log(str2);
     
    // 字符串中嵌入變量
    let name = 'liushi';
    window.location.href = `http://www.baidu.com?name=${name}`;
}

函數的參數默認值

// ES6以前,當未傳入參數時,text = 'default';
function printText(text) {
    text = text || 'default';
    console.log(text);
}

// ES6;
function printText(text = 'default') {
    console.log(text);
}

Spread / Rest 操做符

當被用於迭代器中時,它是一個 Spread 操做符:this

function foo(x,y,z) {
  console.log(x,y,z);
} 
let arr = [1,2,3];
foo(...arr); // 1 2 3

當被用於函數傳參時,是一個 Rest 操做符:當被用於函數傳參時,是一個 Rest 操做符:code

function foo(...args) {
  console.log(args);
}
foo( 1, 2, 3, 4, 5); // [1, 2, 3, 4, 5]

for...of 和 for...in

{
    //返回值
    let letters = ['a', 'b', 'c'];
    letters.size = 3;
    for (let letter of letters) {
      console.log(letter);
    }
    // 結果: a, b, c
    
    //返回鍵,es6
    let stus = ['Sam', '22', '男'];
    stus.size = 3;
    for (let stu in stus) {
      console.log(stu);
    }
    // 結果: 0,1,2,size
}
相關文章
相關標籤/搜索