變量:
?let 堪旧,let具有塊級作用域音五,存在暫時性死區(qū)(在塊級作用域let聲明了一個變量亿汞,它所聲明的變量就被綁定到當(dāng)前這個區(qū)域潘酗,不受外部所影響)撩炊,只有在它(let)聲明的代碼塊中起作用:
for(var j = 0; j < 2 j++) {} console.log(j); // 2
for(let i? = 0; i < 3 i++) {} console.log(i); // 報錯: i 未被定義
const, const用于聲明一個常量崎脉,在一個常量被聲明后,值是不可改變的:
const str=123;? // 聲明一個常量
str=456;// TypeError: Assignment to constant variable.
?let伯顶,const都沒有聲明提升囚灼,只能在聲明后使用,在一個塊級作用域內(nèi)祭衩,同一個變量不能被重復(fù)聲明灶体,在塊級作用域外不能訪問作用域內(nèi)的變量
結(jié)構(gòu)賦值:
對象結(jié)構(gòu):
let node = {
? ? type: "Identifier",
? ? name: "foo"
};??
// 使用結(jié)構(gòu)分配不同的值
let { type, name } = node;
console.log(type); // "Identifier"
console.log(name); // "foo"
數(shù)組結(jié)構(gòu):
let colors = [ "red", "green", "blue" ];
let [ firstColor, secondColor ] = colors;? ?//從colors中分別結(jié)構(gòu)出 red,green掐暮, 未顯式聲明的則會被忽略
console.log(firstColor); // "red"
console.log(secondColor); // "green"
// 也可以直接為自己所需要的元素聲明變量
let colors = [ "red", "green", "blue" ];
let [ , , thirdColor ] = colors;
console.log(thirdColor); // "blue"
混合結(jié)構(gòu):
let node = {
? ? type: "Identifier",
? ? name: "foo",
? ? loc: {
? ? ? ? start: {
? ? ? ? ? ? line: 1,
? ? ? ? ? ? column: 1
? ? ? ? },
? ? ? ? end: {
? ? ? ? ? ? line: 1,
? ? ? ? ? ? column: 4
? ? ? ? }
? ? },
? ? range: [0, 3]
};
let {
? ? loc: { start },????????????????????????????????? ?//?分別將node.loc.start和node.range[0]提取到變量start和startlndex中?
? ? range: [ startIndex ]
} = node;
console.log(start.line); // 1?
console.log(start.column); // 1?
console.log(startIndex); // 0
解構(gòu)模式中的loc和range僅代表它們在node對象中所處的位置(也就是該對象的屬性)蝎抽。當(dāng)使用混合解構(gòu)的語法時,則可以從node提取任意想要的信息? ? ? ? ? ? ? ? ? ? ? ? ??
Promise:
?promise有三種狀態(tài):pending(等待路克,處理中)? ?-->? 1.resolve(完成)? ?2.rejected(失敗樟结,拒絕)
Promise對象中的then方法:
?可以接收構(gòu)造函數(shù)中處理的狀態(tài)變化,then方法有2個參數(shù)精算,第一個函數(shù)接收resolved狀態(tài)的執(zhí)行瓢宦,第二個參數(shù)接收reject狀態(tài)的執(zhí)行。
function fn(num) {
? ? returnnewPromise(function(resolve, reject) {
? ? ? ? if(typeofnum == 'number') {
? ? ? ? ? ? resolve();
? ? ? ? } else {
? ? ? ? ? ? reject();
? ? ? ? }
? ? }).then(function() {
? ? ? ? console.log('參數(shù)是一個number值');
? ? }, function() {
? ? ? ? console.log('參數(shù)不是一個number值');
? ? })
}
fn('hahha');
fn(1234);
then方法的執(zhí)行結(jié)果也會返回一個Promise對象灰羽。因此我們可以進行then的鏈?zhǔn)綀?zhí)行
catch的用法:
getNumber()
.then(function(data){
? ? console.log('resolved');
? ? console.log(data);
})
.catch(function(reason){
? ? console.log('rejected');
? ? console.log(reason);
});
在執(zhí)行resolve的回調(diào)(也就是上面then中的第一個參數(shù))時驮履,如果拋出異常了(代碼出錯了)鱼辙,那么并不會報錯卡死js,而是會進到這個catch方法中
all的用法:
Promise的all方法提供了并行執(zhí)行異步操作的能力玫镐,并且在所有異步操作執(zhí)行完后才執(zhí)行回調(diào)
Promise
.all([runAsync1(), runAsync2(), runAsync3()])
.then(function(results){
? ? console.log(results);
});
用Promise.all來執(zhí)行倒戏,all接收一個數(shù)組參數(shù),里面的值最終都算返回Promise對象恐似。這樣杜跷,三個異步操作的并行執(zhí)行的,等到它們都執(zhí)行完后才會進到then里面蹂喻,all會把所有異步操作的結(jié)果放進一個數(shù)組中傳給then葱椭,就是上面的results