ES6新特性之傻瓜式说明

ES6出来挺长一段时间了,但目前网上好像教程并不多也不详细。我依然遵循傻瓜式教学模式,白话文说明JavaScript和ES6的一些区别,说明下ES6的一些新特性。本文适合新手学习,大神请勿见笑,在下在此班门弄斧了。本文估计要写一段时间,晚上抽空便更新一段。

var和let的区别
var是函数作用域,let是代码块作用域

var a = 12;
if(true){
var a = 5;
console.log(a);
}
console.log(a);
两次都输出5,if模块里a被重新赋予值5;

let b = 12;
if(true){
let b = 5;
console.log(b);
}
console.log(b);
第一次输出5,第二次输出12,let是代码块作用域,代码块里重新let,不会影响代码块外面的a;


let解决变量提升的问题

console.log(a); // undefined
console.log(b); // undefined

var a = 12;
let b = 3;

这里其实会出现类似函数提升一样的效果,也就是对于 js 引擎上面的代码的执行顺序其实是先 var a,再 console.log(a)(所以会输出undefined) ,而let不会出现函数提升的效果;


暂时性死区

var a = 123;
if(true){
a = 456;
let a = 5;
console.log(a);
}

尽管a是全局变量,但是在代码块里let了a,这个代码块便形成封闭作用域,全局变量a也会失效,这时a = 456是在let a之前操作,这时的a是未定义的,所以a = 456这个操作会报错,形成暂时性死区;


块级作用域

{
let a = 5;
console.log(a);
{
console.log(a);
}
}
console.log(a);

第一第二行打印出5,第三行报错,let是代码块作用域,内部声明的函数皆不会影响到作用域的外部;

块级作用域另一个例子:
function f(){
console.log('out');
}
(function(){
if(true){
function f(){
console.log('in');
}
}
f();
}());

ES6环境下输出为out,if模块下函数重定义只在块级内生效,不会影响到块级外;

const的用法

const a;
const a = 5;
let a = 5;

const给变量赋值后,值就不能改变,const定义赋值需同时进行,不可只定义不赋值;
const作用域和let相同,声明的常量也不提升,也存在暂时性死区;


const obj = {
"name": "666"
};
Object.freeze(obj);
obj.name = 'hi';
console.log(obj);

const定义一个对象后,对象虽不能再定义,但是依然可以改变对象中的属性;
如果希望对象中的属性也不可被更改,就用对象冻结方法Object.freeze();


跨模块常量,读取其他js文件中的变量

同目录下constants.js中的代码为:
export const A = 123;
export const B = 'abc';
export const C = '666';

引入constants.js
import * as constants from './constants';
console.log(constants.A); // 123
console.log(constants.B); // abc

import {A,B} from './constants';
console.log(A); // 123
console.log(B); // abc


解构赋值,一种特殊的复制方法

let [a,b,c] = [1,2,3];
console.log(a); // 1

let [a,[b,c],d] = [1,[3],5];
console.log(b); // 3

let [,,c] = ['isA','isB','isC'];
console.log(c); // isC

let [a] = 1; // 报错,=号两边模式必须相同

let [a = 'a'] = []; // 设置默认值
console.log(a); // a

let [a,b = 'isB'] = ['a']; // b设置默认值
console.log(a); // a
console.log(b); // isB

let [a = 'aaa',b] = [undefined,'bbb'];
console.log(a); // aaa
console.log(b); // bbb

let { a } = { b: 'bbb', a: 'aaa' };
console.log(a); // aaa

let { a } = { b: "bbb", c: "ccc" };
console.log(a); // undefined

数组的元素是按次序排列的,变量的取值由它的位置决定;而对象的属性没有次序,变量必须与属性同名;

let { b: a} = { c: 'ccc', b: 'bbb'};
console.log(a); // bbb

let obj = { first: 'hello', second: 'world'};
let { first: f, second: s } = obj;
console.log(f); // hello
console.log(s); // world

真正被赋值的是后者,而不是前者;

let obj = {
p: [
'hello',
{
y: 'world'
}
]
};
let { p: [ x, { y } ] } = obj;
console.log(x); // hello
console.log(y); // world

let x;
{ x } = { x: 'xxx' };
console.log(x); // 语法错误,{ x }会被理解成一个代码块

let x;
({ x } = { x: 'xxx' });
console.log(x); // xxx

字符串的解构赋值
let [a,b,c,d,e] = 'hello';
console.log(a); // h
console.log(b); // e
console.log(c); // l
console.log(d); // l
console.log(e); // o

length属性的解构赋值
let { length: len } = 'hello word';
console.log(len); // 10

其他属性的解构赋值
let { toString: s } = 123;
console.log(isNaN(s)); // true

let { a, b } = { a: null, b: undefined };
console.log(a); // null
console.log(b); // undefined

函数参数解构赋值
function add([x,y]){
return x + y;
}
console.log( add([1,2]) ); // 3

function move({ x = 0, y = 0} = {}){
return { x, y };
}
console.log( move() ); // { x: 0, y: 0 }
console.log( move({ x: 5, y: 9}) ); // { x: 5, y: 9 }
console.log( move({ y:6 }) ); // { x: 0, y: 6 }
console.log( move({}) ); // { x: 0, y: 0 }

变换x,y值
let x = 3, y = 5;
[ x, y ] = [ y, x ];
console.log(x); // 5
console.log(y); // 3

解构赋值取函数返回的数组
function example(){
return [1, 2, 3];
}
let [a, b, c] = example();
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3

解构赋值取函数返回的对象
function example(){
return {
a: 'aaa',
b: 'bbb',
c: 'ccc'
}
}
var { a, b, c } = example();
console.log(a); // aaa
console.log(b); // bbb
console.log(c); // ccc

其他应用
function f([x, y, z]){...}
f([1, 2, 3]);

function f({x, y, z}){...}
f({y: 1, x: 2, z: 3});

解构赋值提取json数据
var jsonData = {
id: 1002,
status: "ok",
data: [
{
age: 23,
name: "quuek"
},
{
age: 20,
name: "huuk"
},
{
age: 18,
name: "asut"
}
]
}
let { id, status, data: list } = jsonData;
console.log(id); // 1002
console.log(status); // ok
console.log(list); // [{ age: 23, name: "quuek"}, ...]


集合遍历
let map = new Map();
map.set('first', 'hello');
map.set('second', 'world');

for(let[key, val] of map){
console.log(key + ' is ' + val); // first is hello second is world
}

获取键名
for (let [key] of map) {
// ...
}

// 获取键值
for (let [,value] of map) {
// ...
}


字符串遍历器
let str = 'a1b2c3d4e5';
for(let item of str){
console.log(item); // a,1,b,2,c,3 ...
}

includes(), startsWith(), endsWith()的使用方法
let str = 'this is a string of test';

let includes = str.includes('es');
let startsWith = str.startsWith('t');
let endsWith = str.endsWith('t');

console.log(includes);
console.log(startsWith);
console.log(endsWith);

let includes2 = str.includes('es', 6);
let startsWith2 = str.startsWith('t', 3);
let endsWith2 = str.endsWith('t', 7);

console.log(includes2);
console.log(startsWith2);
console.log(endsWith2);

使用第二个参数n时,endsWith的行为与其他两个方法有所不同。它针对前n个字符,而其他两个方法针对从第n个位置直到字符串结束。


repeat(n) 将原字符串重复n次
let newab = 'ab'.repeat(3);
console.log(newab); // ababab


传统的JavaScript语言,输出模板通常是这样写的。

$("#result").append(
"There are <b>" + basket.count + "</b> " +
"items in your basket, " +
"<em>" + basket.onSale +
"</em> are on sale!"
);

上面这种写法相当繁琐不方便,ES6引入了模板字符串解决这个问题。
let count = 5, onSale = 'qw';
document.getElementById('result').innerHTML = (`
<p>There are <b>${count}</b> items</p>
<div class="second-line">in your basket, <em>${onSale}</em></div>
are on sale!
`);

普通字符串
`In JavaScript ' ' is a line-feed.`

多行字符串
`In JavaScript this is
not legal.`

console.log(`string text line 1
string text line 2`);

字符串中嵌入变量
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
上面代码中的字符串,都是用反引号表示。如果在模板字符串中需要使用反引号,则前面要用反斜杠转义。

var greeting = `\`Yo\` World!`;
如果使用模板字符串表示多行字符串,所有的空格和缩进都会被保留在输出之中。

$("#warning").html(`
<h1>Watch out!</h1>
<p>Unauthorized hockeying can result in penalties
of up to ${maxPenalty} minutes.</p>
`);
模板字符串中嵌入变量,需要将变量名写在${}之中。

function authorize(user, action) {
if (!user.hasPrivilege(action)) {
throw new Error(
// 传统写法为
// 'User '
// + user.name
// + ' is not authorized to do '
// + action
// + '.'
`User ${user.name} is not authorized to do ${action}.`);
}
}
大括号内部可以放入任意的JavaScript表达式,可以进行运算,以及引用对象属性。

var x = 1;
var y = 2;

`${x} + ${y} = ${x + y}`
"1 + 2 = 3"

未写完,更新中......

原文地址:https://www.cnblogs.com/liqiyuan/p/6545407.html