PHP前端开发

Let、Const 和 Var 概述:主要差异解释

百变鹏仔 3天前 #JavaScript
文章标签 差异

曾经有一段时间,我使用并理解了 javascript 中 let、const 和 var 的实际用法,但用语言解释它是具有挑战性的。如果您发现自己处于类似的困境,那么需要关注的关键点是范围、提升、重新初始化和重新分配方面的差异。

范围:

var 示例(函数和全局作用域)

function varexample() {    if (true) {        var x = 10; // x is function-scoped    }    console.log(x); // outputs: 10}varexample();if (true) {    var y = 20; // y is globally scoped because it's outside a function}console.log(y); // outputs: 20

let 示例(块作用域)

function letexample() {    if (true) {        let x = 10; // x is block-scoped        console.log(x); // outputs: 10    }    console.log(x); // referenceerror: x is not defined}letexample();if (true) {    let y = 20; // y is block-scoped    console.log(y); // outputs: 20}console.log(y); // referenceerror: y is not defined

const 示例(块作用域)

function constexample() {    if (true) {        const x = 10; // x is block-scoped        console.log(x); // outputs: 10    }    console.log(x); // referenceerror: x is not defined}constexample();if (true) {    const y = 20; // y is block-scoped    console.log(y); // outputs: 20}console.log(y); // referenceerror: y is not defined

吊装

提升就像在开始任务之前设置一个工作空间。想象一下你在厨房里,准备做饭。在开始烹饪之前,请将所有食材和工具放在柜台上,以便触手可及。

在编程中,当您编写代码时,javascript 引擎会在实际运行代码之前检查您的代码,并将所有变量和函数设置在其作用域的顶部。这意味着您可以在代码中声明函数和变量之前使用它们。

console.log(myvar); // outputs: undefinedvar myvar = 10;
console.log(mylet);// referenceerror: cannot access 'mylet' before initializationlet mylet = 10;
console.log(myconst); // referenceerror: cannot access 'myconst' before initializationconst myconst = 20;

重新分配和重新初始化:

var x = 10;x = 20; // reassignmentconsole.log(x); // outputs: 20var x = 30; // reinitializationconsole.log(x); // outputs: 30
let y = 10;y = 20; // reassignmentconsole.log(y); // outputs: 20let y = 30; // syntaxerror: identifier 'y' has already been declared
const z = 10;z = 20; // typeerror: assignment to constant variable.const z = 30; // syntaxerror: identifier 'z' has already been declared

const 对象的示例

const obj = { a: 1 };obj.a = 2; // allowed, modifies the propertyconsole.log(obj.a); // outputs: 2obj = { a: 3 }; // typeerror: assignment to constant variable.

const 数组的示例

const arr = [1, 2, 3];arr[0] = 4; // Allowed, modifies the elementconsole.log(arr); // Outputs: [4, 2, 3]arr = [5, 6, 7]; // TypeError: Assignment to constant variable.