關于ES6常用語法

ES6語法跟babel:

一、首先我們來解釋一下什么是ES?

ES的全稱是ECMAScript。1996 11

,JavaScript的創造者Netscape公司,決定將JavaScript提交給國際標準化組織ECMA,希望這種語能夠成為國際標準。

二、什么是ES6?為什么這么火?

ECMAScript 6.0(以下簡稱ES6)是JavaScript語的下代標準,已經在2015 6正式發布。它的標,是使得JavaScript語可以來編寫復雜的型應程序,成為企業級開發語。

2009年開始ECMAScript 5.1版本發布后,其實就開始定制6.0版本了。因為這個版本引入的語法功能太多,且制定過程當中,還有很多組織和個斷提交新功能。事情很快就變得清楚,可能在個版本包括所有將要引的功能。常規的做法是先發布6.0版,過段時間再發6.1版,然后是6.2版、6.3版等等;

三、ES6以及ES7+增加了哪些新特性?有哪些好用的語法?實例:

我們之前聲明一個變量需要var,為什么要增加let、const;再去聲明變量呢?//關于var、let、const關鍵字特性和使用方法;

// let和const都是只在自己模塊作用域內有效{}內

function test() {

if (true) {

let a = 1

console.log(a)

}

console.log(a) //a is not defined;

}

test()

// const和let的異同點

// **相同點:**const和let都是在當前塊內有效,執行到塊外會被銷毀,也不存在變量提升(TDZ),不能重復聲明。

// **不同點:**const不能再賦值,let聲明的變量可以重復賦值。

for (var i = 0; i < 5; i++) {

setTimeout(() => {

console.log(i) //5, 5, 5, 5, 5

}, 0)

}

console.log(i) //5 i跳出循環體污染外部函數

//將var改成let之后

for (let i = 0; i < 5; i++) {

setTimeout(() => {

console.log(i) // 0,1,2,3,4

}, 0)

console.log(’22’);

}

console.log(i)//i is not defined i無法污染外部函數

四、字符串操作

let t = 'abcdefg';

if (t.indexOf('abc') > -1) {

console.log('yes有abc哦??');

}//ES5寫法

// ES6新特性檢測是否包含(如果想看在字符串的位數還是使用indexOf());

if (t.includes('abc')) {

console.log('yes有abc哦??');

}

//檢測是否在頭部

if (t.startsWith('abc')) {

console.log('頭部有abc哦??');

}

//檢測是否在最后

if (t.endsWith('fg')) {

console.log('尾部有fg哦??');

}

//有意思的字符串操作(目前沒發現有啥用)

console.log('哈'.repeat(4))//哈哈哈哈;原版輸出了4遍。。。

//字符串改版之使用模板字面量反撇號``。在實際開發中,這是經常都要用到的方法。

let a = '我是字符串';

let b = `這也是一個字符串哦`;

//ES5字符串換行

let a = '123\n456'

console.log(a)

// 123

// 456

// ES6

let a = `1234

56`;

console.log(a)

//1234

//56

//不再拼接字符串${}來搞定

let a = 'hello'

let b = `${a} world`

console.log(b)// hello world;

五、es6函數

function b(num = 6, callback) {

// num = 6很顯然是默認參數;若傳值則用傳遞的參數否則就用6;

callback(num * num)

}

b(10, data => { console.log(data) })

//不定參數使用...

function add(...ary) {

console.log(ary)

}

let a = 1, b = 9;

add(a, b);//(2) [1, 9]

//展開運算符(...)

//展開運算符的作用是解構數組,然后將每個數組元素作為函數參數。

//有了展開運算符,我們操作數組的時候,就可以不再使用apply來指定上下文環境了。

//ES5的寫法

let arr = [10, 20, 50, 40, 30]

let a = Math.max.apply(null, arr)

console.log(a) // 50

//ES6的寫法

let arr = [10, 20, 50, 40, 30]

let a = Math.max(...arr)

console.log(a) // 50

//箭頭函數

const arr = [5, 10]

const s = arr.reduce((sum, item) => sum+ item)

console.log(s) // 15

//箭頭函數和普通函數的區別是:

// 1、箭頭函數沒有this,函數內部的this來自于父級最近的非箭頭函數,并且不能改變this的指向。

// 2、箭頭函數沒有super

// 3、箭頭函數沒有arguments

// 4、箭頭函數沒有new.target綁定。

// 5、不能使用new

// 6、沒有原型

// 7、不支持重復的命名參數。

const s = a => a;

console.log(s(44))//44;

//箭頭函數還可以輸出對象,在react的action中就推薦這種寫法。

const action = (type, a) => ({

type: "TYPE",

a

})

//箭頭函數給數組排序

const arr = [1, 333, 2, 444, 0, 99]

const s = arr.sort((a, b) => a - b)

console.log(s) // (6) [0, 1, 2, 99, 333,444]

//屬性初始值簡寫法

//ES5

function a(id) {

return {

id: id

};

};

//ES6

const a = (id) => ({

id

})

//對象簡寫法

// ES5

const obj = {

id: 1,

printId: function () {

console.log(this.id)

}

}

// ES6

const obj = {

id: 1,

printId() {

console.log(this.id)

}

}

//屬性名可以傳入變量。而不是字符串了

const id = 5

const obj = {

[`my-${id}`]: id

}

console.log(obj['my-5']) // 5

六、ES6新增Object.is()方法新比較

Object.is(NaN, NaN) //true

Object.is(-0, +0) //false

Object.is(5, '5') //false

Object.is('4', '5') //false

//新增Object.assign()

//對象拼接

var fang = { 'name': 'sb' };

var sz = { 'c': { 'www': 111 } }

Object.assign(fang, sz)

// {name: "sb", c: {…}}c: {www:111}www: 111__proto__: Objectname: "sb"__proto__: Object

七、解構

let obj = { a: 1, b: [111, 222] };

const {a} = obj;

console.log(a);//1

//在我們REACT里面經常用到props傳值,那么肯定用到解構這玩意兒

class Parent extends React.Component {

render() {

const {a = 3, b = 3} = this.props

return

{a}-{b}

}

}

ReactDOM.render(

,

document.getElementById('root')

);

//在瀏覽器渲染1-2,默認值是3-3,但是因為傳遞了新的props進來,執行了解構賦值之后a和b更新了。

//對象再深也不怕了

var obj = {

a: {

b: {

c: {

d: '藏得夠深了'

}

}

}

}

var {a: {b: {c}}} = obj

console.log(c.d)

// VM739: 11藏得夠深了

// undefined

//解構數組

let arr = [1, 2, 3]

//解構前2個元素

const [a, b] = arr

console.log(a, b) //1 2

//解構中間的元素

const [, b,] = arr

console.log(b) // 2

//更進一步了解數組解構

let a = '我是老A';

let ary = [1, 2, 3];

[a] = ary;

console.log(a);//1重新賦值了。

//使用解構變換數組

let a = 11, b = 22;

[a, b] = [b, a];

console.log(a, b)//22 11竟然變換了

//嵌套數組解構

let ary = [1, [1, 2, 3], 4];

let [a, [, b]] = ary;

console.log(a, b)//1,2

//不定元素解構三個點代表了所有元素

ary = [1, 2, 3, 4];

let [...a] = ary;

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

let obj = {

a: { id: 1 }, b: [22, 11]

}

const {a: {id}, b: [...ary]} = obj;

console.log(id, ary);

//解構參數

function ajax(url, options) {

const {timeout = 0, jsonp = true} = options;

}

ajax('baidu.com', { timeout: 1000, jsonp:false });//'baidu.com' 1000,false;

八、Map Set我們都稱之為集合

let set = new Set();

set.add('haha');

set.add(Symbol('huhu'));

console.log(set);

set.has('huhu')//false;

set.has('haha')//true;

// set循環

for (let [value, key] of set) {

console.log(value, key)

}

set.forEach((value, key) => {

console.log(value, key)

})

// set來實現數組去重。。。

const ary = [1, 1, 1, 3, 3, 3, 44, 55, 0,'3', '3']

let sets = new Set(ary);

console.log(sets);

// Set(6) {1, 3, 44, 55, 0,?…}

let set = new Set();

set.add(1); set.add(2);

set.add('1'); set.add('2');

console.log(Array.from(set))

//(4) [1, 2, "1", "2"]

//經典數組去重方法

const arr = [1, 1, 'haha', 'haha', null,null]

let set = new Set(arr);

console.log(Array.from(set)) // [1, 'haha',null]

console.log([...set]) // [1, 'haha', null]

let map = new Map();

map.set('name', '房帥中');

map.set('id', '130*******');

map

// Map(2) {"name" => "房帥中","id" => "130***1992****" }

// size

// :

// (...)

// __proto__

// :

// Map

// [[Entries]]

// :

// Array(2)

// 0

// :

// { "name" => "房帥中" }

// 1

// :

// { "id" =>"130*******" }

// length :

// 2

// es5構造函數寫法

function Person(name) {

this.name = name;

}

Person.prototype.sayName = function () {

return this.name;

}

let p1 = new Person();

console.log(p1.sayName());

//而es6引入了class類學過java的應該知道聲明類的方式‘

class Person {

constructor(name) {

this.name = name//私有屬性

}

sayName() {

return this.name;

}

}

let p2 = new Person('房小帥啊');

console.log(p2.sayName());//房小帥啊

//類聲明和函數聲明的區別和特點

// 1、函數聲明可以被提升,類聲明不能提升。

// 2、類聲明中的代碼自動強行運行在嚴格模式下。

// 3、類中的所有方法都是不可枚舉的,而自定義類型中,可以通過Object.defineProperty()手工指定不可枚舉屬性。

// 4、每個類都有一個[[construct]]的方法。

// 5、只能使用new來調用類的構造函數。

// 6、不能在類中修改類名。

//類聲明方式

//聲明式

class B {

constructor() { }

}

//匿名表達式

let A = class {

constructor() { }

}

//命名表達式,B可以在外部使用,而B1只能在內部使用

let B = class B1 {

constructor() { }

}

九、改進數組的方法

Array.of(); Array.from();//Array.of()是創建一個新數組,而Array.from()是將類數組轉換成數組

const a = new Array(2);

const b = new Array('44');

console.log(a, b)// [empty×2]length:

2__proto__: Array(0) ["44"]這樣導致a的內容不正確;

//正確使用Array.of(2)

let cc = Array.of(2);

console.log(cc) //=> [2];

// Array.from()用法醬類數組轉為數組

function test(a, b) {

let arr = Array.from(arguments)

console.log(arr)

}

test(1, 2) //[1, 2]

// Array.from(a,b)傳入兩個參數,第二個參數作為第一個參數的轉換

function test(a, b) {

let arr = Array.from(arguments, value => value + 2)

console.log(arr)

}

test(1, 2) //[3, 4]

// Array.from還可以設置第三個參數,指定this。

function test() {

return Array.from(new Set(...arguments))

}

const s = test([1, "2", 3, 3,"2"])

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

//給數組添加新方法

find(), findIndex(), fill(), copyWithin();

// find()方法

//找到符合條件的并返回。

const arr = [1, 2, 3, 4, 5, '4'];

arr.find(n => typeof n === 'string')

//找到符合條件的index并返回

const arr = [1, "2", 3, 3,"2"]

console.log(arr.findIndex(n => typeof n=== "string"));//1

// fill()用新元素替換掉數組內的元素,可以指定替換下標范圍

arr.fill(value, start, end);

const arr = [1, 2, 3]

console.log(arr.fill(4)) // [4, 4, 4]不指定開始和結束,全部替換

const arr1 = [1, 2, 3]

console.log(arr1.fill(4, 1)) // [1, 4, 4]指定開始位置,從開始位置全部替換

const arr2 = [1, 2, 3]

console.log(arr2.fill(4, 0, 2)) // [4, 4,

3]指定開始和結束位置,替換當前范圍的元素

// copyWithin()選擇數組的某個下標,從該位置開始復制數組元素,默認從0開始復制,也可以指定要復制的元素范圍。

arr2.copyWithin(target, start, end);

arr2.copyWithin(3, 1);

// Promise生命周期

//進行中pending完成fulfilled拒絕rejected;

// promise被稱為異步結果的占位符,他不能直接返回異步函數的執行結果,需要使用then()當獲取異常回調的時候使用catch();

new Promise(function (resolve, reject) {

setTimeout(() => {

resolve(5), 0

})

}).then(v => console.log(v));

//使用模塊封裝代碼

//數據模塊

const obj = { a: 1 }

//函數模塊

const sum = (a, b) => {

return a + b;

}

//類模塊

class My extends React.Components {

}

//模塊導出

export const obj = { a: 1 }

//函數模塊

export const sum = (a, b) => {

return a + b;

}

//類模塊導出

export class MyClass extendsReact.Components {

// ...

}

//模塊引用

import { obj, my } from './**.js';

// obj.a使用

//全部模塊導入

import * as all from './**.js';

//all.obj,all.sun使用

//默認模塊

function sum(a, b) {

return a + b;

}

export default sum;

//導入import sum from'./**.js';

// react中import React from

'react'; Vue中import sum from './**.js'

//修改模塊導入導出名

// 1.導出時候修改

function sum(a, b) {

return a + b

}

export { sum as add }

import { add } from './xx.js'

add(1, 2);

//導入時修改

function sum(a, b) {

return a + b

}

export default sum;

import { sum as add } from './xx.js'

add(1, 2);

//無綁定導入

let a = 1; const PI = '3.1415';

//導入的時候

import './**.js';

console.log(a, PI);

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容