JavaScript let 和 const
<p>在JavaScript中,我們有兩個(gè)關(guān)鍵字 "let" 和 "const",用于聲明變量。</p>
<h2>let 聲明</h2>
<p>"let" 關(guān)鍵字用于聲明一個(gè)塊級(jí)作用域的變量。</p>
<pre><code>
// 使用 let 聲明變量
let x = 10;
// 在同一作用域內(nèi)重新賦值
x = 20;
// 在不同的作用域內(nèi)使用 let 聲明變量
function example() {
let y = 30;
console.log(x); // 輸出:20
console.log(y); // 輸出:30
}
console.log(x); // 輸出:20
console.log(y); // 報(bào)錯(cuò):y is not defined
<h2>const 聲明</h2>
<p>"const" 關(guān)鍵字用于聲明一個(gè)常量,一旦聲明后就不能再被修改。</p>
<pre><code>
// 使用 const 聲明常量
const PI = 3.14159;
// 嘗試重新賦值
PI = 3.14; // 報(bào)錯(cuò):Assignment to constant variable.文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-474130.html
// 聲明一個(gè)對(duì)象常量
const person = {
name: ‘John’,
age: 30
};文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-474130.html
到了這里,關(guān)于【34JavaScript let 和 const】JavaScript中的“l(fā)et“和“const“關(guān)鍵字詳解:作用、用法及區(qū)別的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!