ES6新增的一些常用特性


https://www.cnblogs.com/canfoo/p/5896927.html

這篇寫的非常好,及時雨

我完全復制了過來,方便以后查看

幾個ES6新特性

ES6是JavaScript語言的下一代標准,已經在2015年6月正式發布了,因為ES6的第一個版本是在2015年發布的,所以又稱ECMAScript 2015(簡稱ES2015)。本文主要講述的是ES6相對於ES5的幾個實用新特性,如有其它見解,歡迎指正和交流。

在線babel轉換地址:http://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=es2015%2Creact%2Cstage-2&code=

1. let關鍵字

(1)基本用法:let關鍵字用來聲明變量,它的用法類似於var,都是用來聲明變量。

(2)塊級作用域:let聲明的變量,只在let關鍵字所在的代碼塊內有效。

復制代碼
{
  var a = 10;
  let b = 10;
}
console.log(a);  //10
console.log(b);  //error: b is not defined
  
var c = 10;
{
  var c = 20;
}
console.log(c);  //20
  
var d = 10;
{
  let d = 20;
}
console.log(d);  //10

var i=0;
for(var i=0; i<10; i++) {
}
console.log(i);  //10

var j=0;
for(let j=0; j<10; j++) {
}
console.log(j);  //0
復制代碼

(3)不存在變量提升:let聲明的變量一定要在聲明后使用,否則會報錯

console.log(a);  //undefined
console.log(b);  //error: b is not defined

var a = 10;
let b = 10;

 2. const關鍵字

(1)基本用法:聲明一個只讀的常量。一旦聲明,常量的值就不能改變。

console.log(a);  //undefined
console.log(b);  //error: b is not defined
var a = 10;
let b = 10;

 (2)其他特性與var關鍵字一致

 3. 字符串拼接方法

(1)基本用法:用反引號進行拼接 

復制代碼
/*ES5中字符串處理方法*/
var name = "Jack";
var str1 = 'my name is ' + name;
console.log(str1);  //my name is Jack

/*ES6中字符串處理方法*/
var str2 = `my name is ${name}`;
console.log(str2);  //my name is Jack
復制代碼

4. function函數

(1)基本用法:默認參數

復制代碼
/*ES5中函數默認參數處理方法*/
function fn1(height) {
    var height = height || 100;
    console.log(height);
}
fn1();  //100

/*ES6中直接在形參賦值進行設置默認參數*/
function fn2(height = 100) {
    console.log(height);
}
fn2();  //100
復制代碼

(2)箭頭函數

復制代碼
/*ES5中定義一個函數變量*/
var fn1 = function(height) {
    console.log(height);
}
fn1(100);  //100

/*ES6中用箭頭函數定義函數變量*/
var fn2 = (height) => {
    console.log(height);
}
fn2(100);  //100
復制代碼
復制代碼
/*箭頭函數特性:箭頭函數的this指針保持和外層指針一致*/
var ele = document.getElementById('ele');  //獲取某個元素,綁定點擊事件
ele.onclick = function() {
    setTimeout(function() {
        console.log(this);   //點擊后,打印出window對象
    }, 10)
}
ele.onclick = function() {
    setTimeout(() ()=> {
        console.log(this);   //點擊后,打印出ele元素對象
    }, 10)
}
復制代碼
復制代碼
/*箭頭函數特性:箭頭函數的argumets對象和外層一致*/
function fn1(height) {
    setTimeout(function() {
        console.log(arguments);
    }, 10)
}
function fn2(height) {
    setTimeout(() => {
        console.log(arguments);
    }, 10)
}
fn1(100);  //[]
fn2(100);  //[100]
復制代碼

5. 變量的結構賦值

(1)基本用法

復制代碼
/*ES5初始化變量*/
var a = 10;
var b = 20;

/*ES6解構賦初值*/
var [a, b] = [10, 20];
復制代碼
復制代碼
/*ES5獲取對象的key值*/
var obj1 = {
    username1: 'jack',
    password1: 123
}
var username1 = obj1.username1;
var password1 = obj1.password1;
console.log(username1, password1);

/*ES6通過解構拆包獲取對象的key值*/
var obj2 = {
    username2: 'jack',
    password2: 123
}
var {username2, password2} = obj2;
console.log(username2, password2);
復制代碼
/*字符串的解構賦值*/
var [a, b, c, d, e] = 'hello';
console.log(a, b, c, d, e);  //h e l l o
/*數組的解構賦值*/
var [a, b, c] = ['hello', 'world'];
console.log(a, b, c);  //hello world

6. …拓展操作符

 (1)基本用法

復制代碼
//合並數組
var arry = ['a', 'b'];
var arry1 = arry.concat(['c']);  //ES5數組拼接
var arry2 = [...arry, 'c'];  //ES6...操作符拼接數組
console.log(arry1); //['a', 'b', 'c']
console.log(arry2);  //['a', 'b', 'c']

//合並對象
var obj = {a: 1, b: 2};
var obj1 = {...obj, c: 3};
var obj2 = {...obj, a: 3};
console.log(obj1) ; // {a: 1, b: 2, c: 3}
console.log(obj2) ; // {a: 99, b: 2}
復制代碼
/*拆分字符串*/
console.log([...'hello']); // [ "h", "e", "l", "l", "o" ]
復制代碼
/*合並成數組*/
function mergeArr(...Arrys) {
    console.log(arguments);
}
mergeArr('a', 'b', 'c');  //['a', 'b', 'c'];

/*拆分數組*/
console.log(...['a', 'b', 'c']);  //a b c
復制代碼
復制代碼
function fn1() {
    var arry = Array.prototype.sort.call(arguments, function(a, b) {
        return a - b;
    })
    console.log(arry);
}
fn1(3,1,5,3,8,6);  //1 3 3 5 6 8

/*...操作符將類數組轉換為數組*/
function fn2() {
    var arry = [...arguments].sort(function(a, b) {
        return a - b;
    })
    console.log(arry);
}
fn2(3,1,5,3,8,6);  //1 3 3 5 6 8
復制代碼

7. 對象的一些實用方法

(1)Object.is():判斷兩個值是否相等,ES5比較兩個值是否相等,只有兩個運算符:相等運算符(==)和嚴格相等運算符(===)。它們都有缺點,前者會自動轉換數據類型,后者的NaN不等於自身,以及+0等於-0。

console.log(+0 === -0)  //true,錯誤結果
console.log(NaN === NaN)  //false,錯誤結果
console.log(Object.is(+0, -0)) // false,正確結果
console.log(Object.is(NaN, NaN)) // true,正確結果
/*普通值的比較*/
console.log(Object.is('foo', 'foo')) //true
console.log(Object.is({}, {}))  //false

(1)Object.assign():合並對象的方法,將源對象(source)的所有可枚舉屬性,復制到目標對象(target)。

/*使用方法*/
var target = {a: 1, b: 1 };
var source = {c: 1};
console.log(Object.assign(target, source));  //{a: 1, b: 1, c: 1}
/*如果目標對象與源對象有同名屬性,或多個源對象有同名屬性,則后面的屬性會覆蓋前面的屬性*/
var target = {a: 1, b: 1 };
var source = {a: 20, c: 1};
console.log(Object.assign(target, source));  //{a: 20, b: 1, c: 1}
復制代碼
/*運用:克隆對象*/
function clone(origin) {
  return Object.assign({}, origin);
}
var obj1 = {
    a: 2
}
var obj2 = clone(obj1);
console.log(obj2);  //{a: 2}

/*注意:Object.assign方法實行的是淺拷貝,而不是深拷貝。也就是說,如果源對象某個屬性的值是對象,那么目標對象拷貝得到的是這個對象的引用。*/
var obj1 = {a: {b: 1}, c: 1};
var obj2 = Object.assign({}, obj1);
obj2.a.b = 100;
obj2.c = 200;
console.log(obj1);  //{a: {b: 100}, c: 1}
復制代碼
/*運用:合並對象*/
var merge = (...sources) => Object.assign({}, ...sources);
console.log(merge({a: 1}, {b: 2}, {a: 3, c :3}));  //{a: 3, b: 2, c: 3}

8. promise對象

(1)定義:一種異步函數的解決方案,避免了異步函數層層嵌套,將原來異步函數轉換 為便於理解和閱讀的鏈式步驟關系

(2)三種狀態:Pending(進行中)、Resoloved(已完成)、Rejected(已失敗)。

(3)兩種結果:Pending->Resoloved(成功); Pending->Rejected(失敗)。

(4)then方法:第一個參數是成功時調用的函數,第二個參數是失敗時調用的函數。

(5)通常形式。

復制代碼
var promise = new Promise((reslove, reject) => {
    if(條件成立) {
        /*Pending->Resoloved(成功*/
        reslove(); 
    }else {
        /*Pending->Rejected(失敗)*/
        reject();
    }
})
復制代碼
復制代碼
/*運用:隔1s打印‘hello’,隔2s打印‘world’*/

/*ES5實現方法*/
setTimeout(function(){
    console.log('hello')
      setTimeout(function(){
        console.log('world')
      }, 1000)
}, 1000)  

/*Promise實現方法*/
var wait1000 = (str) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(str);
        }, 1000)
    })
}

wait1000('hello').then((data) => {
    console.log(data);
    return wait1000('world');
}, () => {
    console.log('err');
}).then((data) => {
    console.log(data);
})
復制代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM