ES6 Javascript

This is some note from the Udemy course: ES6 Javascript: The Complete Developer's Guide

Array Helper Method

forEach: take place of for loop, function is iterator function

colors.forEach(function(color) {
    console.log(color);
}); 
function adder(number) {
    sum += number;
}
numbers.forEach(adder);

map

var numbers = [1,2,3];
var doubled = numbers.map(function(number) {
    return number * 2;
});

filter (should return boolean)

products.filter(function(product) {
    return product.type === 'vegetable' 
        && product.price < 10;
})

var numbers = [1,2,30];
var lessThanFive = reject(numbers, function(item) {
    return item >= 5;
});
function reject(array, iteratorFunction) {
  return array.filter(function(number){
      return !iteratorFunction(number);
  });
}

find: will break the loop once the iterator function returns true (should return boolean)

users.find(function(user) {
    return user.name === 'Alex';
});

every (should return boolean)

computers.every(function(computer) {
    return computer.ram > 16;
})

some (should return boolean)

computers.some(function(computer) {
    return computer.ram > 16;
})

reduce: condensing the whole array into a single value

  • here, 0 is an initial value
  • the first parameter of the passed function has an accumulative state of values, which has the same type of the initial value
  • the second parameter is every single value in the numbers array
  • return changed value at the end
numbers.reduce(function(sum, number) {
    return sum + number;
}, 0)
  • check balanced parameters
  • if the final sum result is 0, it is balanced
  • if '(', we add one to previous
  • if ')', we reduce one to previous
  • if not parenthesis, return the same value
  • if negative, return the same value so that finally the sum won't be true. negative means the parenthesis is out of order
function balanceParens(string) {
    return !string.split("").reduce(function(previous, char) {
      if (previous < 0) { return previous; }
      if (char == '(') { return ++previous; }
      if (char == ')' { return --previous; }
      return previous;
    }, 0)
}

Const and Let

  1. const = var that never changes
  2. let = var that is variable

Template Strings

之前我们要用引号把变量和string分开,现在用一个backstick(`),我们可以将变量和string都包括在backstrick里面,用${}把变量给围起来,还可以对它进行运算。

"This year is " + year
---
`The year is ${year + 2}`

Arrow Functions

Replace function to a fat arrow

const add = function(a, b) {
    return a + b;
}
=================================
const add = (a, b) => {
    return a + b;
}
=================================
// 因为在{}中只有一个return statement, we can further simplify it into
// implicit return
const add = (a, b) => a + b; 
=================================
如果我们只有一个变量传入的话,可以把括号也省了,也可以把分号(semicolon)也省了
const double = number => 2 * number
=================================
// solve binding this problem
const team = {
    members: ['Jane', 'Bill'],
    teamName: 'Super Sqad',
    teamSummary: function() {
      var self = this;
      return this.members.map((member) =>
          return `${member} is on team ${self.teamName}` // change this to self
      });
    }
};

// use bind this
const team = {
    members: ['Jane', 'Bill'],
    teamName: 'Super Sqad',
    teamSummary: function() {
      return this.members.map((member) =>
          return `${member} is on team ${this.teamName}`
      }.bind());
    }
};

// use lexical this
// this === team
const team = {
    members: ['Jane', 'Bill'],
    teamName: 'Super Sqad',
    teamSummary: function() {
      return this.members.map((member) =>
          return `${member} is on team ${this.teamName}`
      });
    }
};

Enhanced Object Literals

function createBookShop(inventory) {
    return {
      inventory, // inventory: inventory
      inventoryValue() { // inventoryValue: function()
        return this.inventory.reduce((total, book) => total + book.price;
      }
    }
}
function saveFile(url, data) {
    $.ajax({ url, data, method: "POST"}); // url: url, data: data
}

Default Function Arguments

function makeAjaxRequest(url, method = 'GET') {}
makeAjaxRequest(url, null); // method will be set to undefined

Rest and Spread Operator

...这个东西会把一个container里的东西spread out成一个个单独的个体,然后再将它们变为a list。

const color = ['red, 'green']
const favorite = ['orange', 'yellow']
const color2 = ['fire red']
[ 'blue', ...color, ...favorite, ...color2] => ['red, 'green', 'orange', 'yellow', 'fire red' ]
function validateShoppingList(...items) {
  if (items.indexOf('milk') < 0) {
     return [ 'milk', ...items];
  }
  return items;
}

Destructuring

我们所要创建的变量和要引用的变量名字必须一致。
You can pull a variable of an object(use {})or an array(use []) which would reduce the amount of code you have to write!

var expense = {
    type: 'Business',
    amount: '$45 USD'
};

// I want to create a new variable type, which refers to expense.type property
const { type } = expense;
const { amount }  = expense;

// even simpler
const { type, amount } = expense
var savedFiled = {
    extension: 'jpg',
    name: 'repost',
    size: 14040
};

function fileSummary({ name, extension, size }, { color }) {
    return `${color} The file ${name}.${extension} is of size ${size}`;
}

fileSummary(savedFiled, { color: 'red' });
const companies = [
    'Google', 
    'Facebook',
    'Uber'
];

const [ name1, name2 ] = companies;
name1 === 'Google'  // true
name2 === 'Facebook' // true

const [name, ...rest] = companies
name === 'Google' // true
rest === ['Facebook', 'Google'] // true
const companies = [
    { name: 'Google', location: 'Mountain View' },
    { name: 'Facebook', location: 'Menlo Park' }
]

const [location] = companies;
location === { name: 'Google', location: 'Mountain View' } // true
const [{location}] = companies;
location === 'Mountain View' // true
const Google = {
    locations : [ 'Mount View', 'New York', 'London' ]
};
const { locations: [ location ] } = Google
location === 'Mount View' // true

Classes to Implement Prototype Inheritance

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

    drive() {
        return 'vroom';
    }
}

class Toyota extends Car {
    constructor(options) {
        super(options);
        this.color = options.color;
    }
    honk() {
      return 'beep';
    }
}
const car = new Car({ title: 'Toyota' });
const t = new Toyota({ title: 'Toyota', color: 'red' });

Generators

Simple Use

function* colors() {
    yield 'red';
    yield 'blue';
    yield 'green';
}

const gen = colors();
gen.next(); // red, done:false
gen.next(); // blue, done:false
gen.next(); // green, done: false
gen.next(); // done: true

// that is the same as 
const myColors = [ ]
for (left color of colors()) {
    myColors.push(color);
}

An example to show:

  1. how values are passed in and out for yield
  2. how return statements are used in the generator, and why it is not the best choice (in for...of loop, it will throw away the return statement, while in the generator iterator(.next()), it won't)
function *foo(x) {
    var y = 2 * (yield (x + 1));
    var z = yield (y / 3);
    return (x + y + z);
}

var it = foo( 5 );

// note: not sending anything into `next()` here
// what we sent in is the return place for the last yield
console.log( it.next() );       // { value:6, done:false }

// we sent in 12, which goes to the line var y = 2 * (yield(x + 1))
// it.next() will return to line var z = yield (y / 3);
console.log( it.next( 12 ) );   // { value:8, done:false }

console.log( it.next( 13 ) );   // { value:42, done:true }

Use Symbolic.iterator which is a special object to tell for...of loop how to iterate an object.

Promises

// only resolve the request after 3000ms
const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve();
    }, 3000);
});

// the most common usage
url = "https://www.abc.com"
fetch(url) // this will return a promise
    .then(response => response.json())
    .then(data => console.log(data)) // json data
    // a big pitfall: it doesn't catch errors of 404, because it has actually reach the server and return a failed status code. Only when the request can't reach a server will an error be caught.
    .catch(error => console.log('BAD', error));

promise
    .then(() => console.log('appear after resolved'))
    .then(() => console.log('a chain of then!'))
    .catch(() => console.log('uh oh!! something bad happens'));
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,544评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,430评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,764评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,193评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,216评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,182评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,063评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,917评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,329评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,543评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,722评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,425评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,019评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,671评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,825评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,729评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,614评论 2 353

推荐阅读更多精彩内容