ES6

前言:

Babel 转码器  可以将 ES6 代码转为 ES5 代码,从而在现有环境执行 你可以用 ES6 的方式编写程序,又不用担心现有环境是否支持

Babel在线转码:https://babeljs.io/repl/

1.添加let、const:

  • ES6 新增了let命令,用来声明变量。它的用法类似于var,但是所声明的变量,只在let命令所在的代码块内有效。
  • const声明一个只读的常量。一旦声明,常量的值就不能改变。

2.解构赋值:

数组的解构赋值

let [a, b, c] = [1, 2, 3];

 对象的解构赋值

let { foo, bar } = { foo: "aaa", bar: "bbb" }; 等价于

let { foo: foo, bar: bar } = { foo: "aaa", bar: "bbb" };

 字符串的解构赋值

const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"

 

3.String扩展:

ES6 又提供了三种新方法

  • includes():返回布尔值,表示是否找到了参数字符串。
  • startsWith():返回布尔值,表示参数字符串是否在原字符串的头部。
  • endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部。
  • repeat():将原字符串重复n次
  • padStart():用于头部补全
  • padEnd():用于尾部补全
let s = 'Hello world!';

s.startsWith('Hello') // true
s.endsWith('!') // true
s.includes('o') // true

s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true
s.includes('Hello', 6) // false

'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""

'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'

'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'

 

 模板字符串: 所有模板字符串的空格和换行,都是被保留的,比如<ul>标签前面会有一个换行。如果你不想要这个换行,可以使用trim方法消除它

$('#list').html(`
<ul>
  <li>${name}</li>
  <li>second</li>
</ul>
`.trim());

 4.函数扩展:

设置入参默认值

function m1({x = 0, y = 0} = {}) {
  return [x, y];
}

参数必填:

function throwIfMissing() {
  throw new Error('Missing parameter');
}

function foo(mustBeProvided = throwIfMissing()) {
  return mustBeProvided;
}

foo()
// Error: Missing parameter

参数选填:

function foo(optional = undefined) { ··· }


rest 参数

function push(array, ...items) {
  items.forEach(function(item) {
    array.push(item);
    console.log(item);
  });
}

var a = [];
push(a, 1, 2, 3)

箭头函数

var f = v => v;

// 等同于
var f = function (v) {
  return v;
};
:: 双冒号运算符:

foo::bar;
// 等同于
bar.bind(foo);

import { map, takeWhile, forEach } from "iterlib";

getPlayers()
::map(x => x.character())
::takeWhile(x => x.strength > 100)
::forEach(x => console.log(x));

 

扩展运算符(spread)是三个点(...)

console.log(...[1, 2, 3])
// 1 2 3

console.log(1, ...[2, 3, 4], 5)
// 1 2 3 4 5

[...document.querySelectorAll('div')]
// [<div>, <div>, <div>]

 

posted @ 2018-05-03 15:28  zark_猿人  阅读(111)  评论(0编辑  收藏  举报