第二話:變量聲明

var聲明

聲明的為全局變量。

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

? ? setTimeout(() => {

? ? ? ? console.log(i);

????}, 100 * i)

}

結(jié)果:10,10,10,。。。。。。(10個(gè))

let聲明

聲明的變量為局部變量,作用域?yàn)閴K作用域。

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

? ? setTimeout(() => {

? ? ? ? console.log(i);

????}, 100 * i)

}

結(jié)果: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

const聲明

const和let擁有相同的作用域規(guī)則,只是const不能被賦值。其實(shí)也只是不能整體賦值,給單獨(dú)的元素賦值是合法的。

const all = {

? ? name: 'xiaoming',

? ? age: 10,

};

// error

all = {

? ? name: 'honghong',

? ? age: 18,

};

// right

all.name = 'honghong';

all.age++;

let vs const

使用原則:最小特權(quán)原則,既所有變量的定義,除了你計(jì)劃去修改的,都應(yīng)該使用const去定義。

解構(gòu)

數(shù)組解構(gòu)

let [ 1, 2 ] = input;

最簡(jiǎn)單的結(jié)構(gòu):

let [ first, second ] = input;

console.log(first); // 1

console.log(second); // 2

作用于函數(shù)參數(shù):

function f([ first, second ]: [ number, number ] ) {

? ? console.log(first, second);?

}

f(input); // 1, 2

可以在數(shù)組里使用...語(yǔ)法創(chuàng)建剩余變量:

let [ first, second, ...rest ] = [ 1, 2, 3, 4 ];

console.log(first, second); // 1, 2

console.log(rest);? // [ 3, 4 ]

你可以忽略你不關(guān)心的元素:

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

console.log(first); // 1

let [ , second, , fourth ] = [ 1, 2, 3, 4 ];

console.log(second, fourth); // 2, 4

對(duì)象解構(gòu)

let person = {

? ? name: 'xiaoxiao',

? ? school: 'beijing',

? ? age: 12,

};

最簡(jiǎn)單的形式:

let { name } = person; // 'xiaoxiao'

let { name, ...rest} = person;

console.log(name); // 'xiaoxiao'

console.log(rest); // { school: 'beijing', age: 12 }

屬性重命名:新名稱寫在冒號(hào)后面

let { name: newName, school: newSchool } = person;

默認(rèn)值:

function keep(ol: { a: number, b?: number }) {

? ? let { a, b = 1002 } = ol;

} // 當(dāng)沒(méi)有傳入b參數(shù)時(shí),b變量使用默認(rèn)值1002

展開

數(shù)組展開:

let first = [ 1, 2 ];

let second = [ 3, 4 ];

let third = [ ...first, ...second, 5]; // [ 1, 2, 3, 4, 5 ]

對(duì)象展開:

let first = {

? ? name: 'apple',

? ? color: 'red',

};

let second = {

? ? price: 4,

? ? size: 'big',

};

let all = { ...first, ...second, color: 'yellow' }; // { name: 'apple', color: 'yellow', price: 4, size: 'big' }

注意:當(dāng)展開一個(gè)對(duì)象實(shí)例時(shí),會(huì)丟失其方法。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容