ECMAScript 6 引入了许可声明。

我听说它被描述为一个当地变量,但我仍然不确定它是如何行为不同于 var 关键词。

什么是差异?什么时候应该被允许使用而不是 var?


下面是让关键词的解释,有几个例子。

主要区别在于,一个变量的范围是整个关闭功能。

此图在维基百科上显示哪些浏览器支持JavaScript 1.7.

请注意,只有 Mozilla 和 Chrome 浏览器支持它. IE、Safari 和其他可能不支持它。

有一些微妙的差异 - 让滑动行为更像变量滑动在更多或更少的任何其他语言。

例如,它转向封锁区块,它们在被宣布之前不存在,等等。

然而,值得注意的是,让它只是新的JavaScript实施的一部分,并且有不同的浏览器支持程度。

函数运行() { var foo = “Foo”; let bar = “Bar”; console.log(foo, bar); // Foo Bar { var Moo = “Mooo” let baz = “Bazz”; console.log(moo, baz); // Mooo Bazz } console.log(moo); // Mooo console.log(baz); // ReferenceError } run();

為什麼讓關鍵字被引入到語言是功能範圍是混亂的原因,是JavaScript的主要錯誤來源之一。

创建全球对象财产

在最高层次上,让我们不同于VAR,不会在全球对象上创造任何财产:

var foo = “Foo”; // 全球推翻的Let bar = “Bar”; // 不允许全球推翻的console.log(window.foo); // Foo console.log(window.bar); // undefined

// An array of adder functions.
var adderFunctions = [];

for (var i = 0; i < 1000; i++) {
  // We want the function at index i to add the index to its argument.
  adderFunctions[i] = function(x) {
    // What is i bound to here?
    return x + i;
  };
}

var add12 = adderFunctions[12];

// Uh oh. The function is bound to i in the outer scope, which is currently 1000.
console.log(add12(8) === 20); // => false
console.log(add12(8) === 1008); // => true
console.log(i); // => 1000

// It gets worse.
i = -8;
console.log(add12(8) === 0); // => true

上面的过程不会产生所需的函数序列,因为我的范围超越了每个函数创建的区块的 iteration。 相反,在环节结束时,每个函数的 i 关闭指在环节结束时的 i 值(1000)为每个在 adder 中的匿名函数。

// Let's try this again.
// NOTE: We're using another ES6 keyword, const, for values that won't
// be reassigned. const and let have similar scoping behavior.
const adderFunctions = [];

for (let i = 0; i < 1000; i++) {
  // NOTE: We're using the newer arrow function syntax this time, but 
  // using the "function(x) { ..." syntax from the previous example 
  // here would not change the behavior shown.
  adderFunctions[i] = x => x + i;
}

const add12 = adderFunctions[12];

// Yay! The behavior is as expected. 
console.log(add12(8) === 20); // => true

// i's scope doesn't extend outside the for loop.
console.log(i); // => ReferenceError: i is not defined

每个函数现在保留在函数创建时的 i 的值,并且 adderFunctions 按照预期行事。

现在,图像将两种行为混合在一起,你可能会看到为什么不建议在同一脚本中混合更新的Let和 const。

const doubleAdderFunctions = [];

for (var i = 0; i < 1000; i++) {
    const j = i;
    doubleAdderFunctions[i] = x => x + i + j;
}

const add18 = doubleAdderFunctions[9];
const add24 = doubleAdderFunctions[12];

// It's not fun debugging situations like this, especially when the
// code is more complex than in this example.
console.log(add18(24) === 42); // => false
console.log(add24(18) === 42); // => false
console.log(add18(24) === add24(18)); // => false
console.log(add18(24) === 2018); // => false
console.log(add24(18) === 2018); // => false
console.log(add18(24) === 1033); // => true
console.log(add24(18) === 1030); // => true

不要让这件事发生在你身上,使用灯具。

下面是两者之间的区别的例子:

正如你可以看到的那样, var j 变量仍然在 loop 范围之外有一个值(区块范围),但 let i 变量在 loop 范围之外是不确定的。

“使用严格”; console.log(“var:”); for (var j = 0; j < 2; j++) { console.log(j); } console.log(j); console.log(“let:”); for (let i = 0; i < 2; i++) { console.log(i); } console.log(i);

此分類上一篇: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p> 點擊每個數字將登錄到主機:</p> <div id="div1">1</div> <div id="div2">2</div> <div id="div3">3</div> <div id="div4">4</div> <div id="div5">5</div>

每个单点处理器都会提到相同的对象,因为只有一个对象对象持有6个,所以你每次点击获得6个。

一个通用工作是将此插入一个匿名功能,并将它作为一个论点。 这种问题现在也可以通过使用,而不是在下面的代码中显示的变化来避免。

答案缺少一点:

{
  let a = 123;
};

console.log(a); // ReferenceError: a is not defined

显然,至少在Visual Studio 2015中,TypeScript 1.5,“var”允许一个区块中的相同变量名称的多个声明,而“Let”不。

这不会导致编译错误:

var x = 1;
var x = 2;

这将是:

let x = 1;
let x = 2;

以下两个功能可以显示差异:

function varTest() {
    var x = 31;
    if (true) {
        var x = 71;  // Same variable!
        console.log(x);  // 71
    }
    console.log(x);  // 71
}

function letTest() {
    let x = 31;
    if (true) {
        let x = 71;  // Different variable
        console.log(x);  // 71
    }
    console.log(x);  // 31
}

相反, var 可以像下面那样粘贴。 { console.log(cc); // undefined. 由于粘贴 var cc = 23; } { console.log(bb); // ReferenceError: bb 没有定义 let bb = 23; } 事实上, Per @Bergi, 两者都是粘贴。

使用 var 声明定义的变量在其定义的整个函数中已知,从函数的开始。 (*) 使用 let 声明定义的变量仅在其定义的区块中已知,从其定义的时刻开始。

// i IS NOT known here
// j IS NOT known here
// k IS known here, but undefined
// l IS NOT known here

function loop(arr) {
    // i IS known here, but undefined
    // j IS NOT known here
    // k IS known here, but has a value only the second time loop is called
    // l IS NOT known here

    for( var i = 0; i < arr.length; i++ ) {
        // i IS known here, and has a value
        // j IS NOT known here
        // k IS known here, but has a value only the second time loop is called
        // l IS NOT known here
    };

    // i IS known here, and has a value
    // j IS NOT known here
    // k IS known here, but has a value only the second time loop is called
    // l IS NOT known here

    for( let j = 0; j < arr.length; j++ ) {
        // i IS known here, and has a value
        // j IS known here, and has a value
        // k IS known here, but has a value only the second time loop is called
        // l IS NOT known here
    };

    // i IS known here, and has a value
    // j IS NOT known here
    // k IS known here, but has a value only the second time loop is called
    // l IS NOT known here
}

loop([1,2,3,4]);

for( var k = 0; k < arr.length; k++ ) {
    // i IS NOT known here
    // j IS NOT known here
    // k IS known here, and has a value
    // l IS NOT known here
};

for( let l = 0; l < arr.length; l++ ) {
    // i IS NOT known here
    // j IS NOT known here
    // k IS known here, and has a value
    // l IS known here, and has a value
};

loop([1,2,3,4]);

// i IS NOT known here
// j IS NOT known here
// k IS known here, and has a value
// l IS NOT known here


今天使用安全吗?

有些人会说,在未来,我们只会使用让陈述,而这些陈述会变得过时。JavaScript老师Kyle Simpson写了一篇非常复杂的文章,他认为为什么不会这样。

事实上,我们实际上需要问自己是否安全使用放弃声明,这个问题的答案取决于你的环境:

此分類上一篇


如何跟踪浏览器支持


ECMAScript 6 添加了另一个关键字来宣布变量,而不是“放下”。

“Let”和“Let”在“var”上引入的主要目标是,而不是传统的词汇,区块点点点点点点点点点点点点点点点点点点点点点点点点。

现在我认为有更好的转换变量到一个区块的声明使用允许:

function printnums()
{
    // i is not accessible here
    for(let i = 0; i <10; i+=)
    {
       console.log(i);
    }
    // i is not accessible here

    // j is accessible here
    for(var j = 0; j <10; j++)
    {
       console.log(j);
    }
    // j is accessible here
}

我认为人们会开始使用Let Here之后,以便他们在JavaScript中与其他语言、Java、C#等类似的分解。

没有对JavaScript的漏洞的明确理解的人早就犯了错误。

Hoisting 不支持使用Let。

在此方法中,在JavaScript中存在的错误正在被删除。

提到ES6在深度:让它更好地理解。

让它很有趣,因为它允许我们做这样的事情:

(() => {
    var count = 0;

    for (let i = 0; i < 2; ++i) {
        for (let i = 0; i < 2; ++i) {
            for (let i = 0; i < 2; ++i) {
                console.log(count++);
            }
        }
    }
})();

其次,有数以数以数。

在哪里

(() => {
    var count = 0;

    for (var i = 0; i < 2; ++i) {
        for (var i = 0; i < 2; ++i) {
            for (var i = 0; i < 2; ++i) {
                console.log(count++);
            }
        }
    }
})();

只有数数(0,1 )。

一些黑客与Let:

1。

    let statistics = [16, 170, 10];
    let [age, height, grade] = statistics;

    console.log(height)

二。

    let x = 120,
    y = 12;
    [x, y] = [y, x];
    console.log(`x: ${x} y: ${y}`);

3、

    let node = {
                   type: "Identifier",
                   name: "foo"
               };

    let { type, name, value } = node;

    console.log(type);      // "Identifier"
    console.log(name);      // "foo"
    console.log(value);     // undefined

    let node = {
        type: "Identifier"
    };

    let { type: localType, name: localName = "bar" } = node;

    console.log(localType);     // "Identifier"
    console.log(localName);     // "bar"

Getter 和 Setter 與 Let:

let jar = {
    numberOfCookies: 10,
    get cookies() {
        return this.numberOfCookies;
    },
    set cookies(value) {
        this.numberOfCookies = value;
    }
};

console.log(jar.cookies)
jar.cookies = 7;

console.log(jar.cookies)

如果我正确地阅读规格,那么幸运的是,也可以被利用,以避免自我呼吁的功能,用于模拟私人成员 - 一个流行的设计模式,减少代码的可读性,复杂的漏洞,没有添加真正的代码保护或其他好处 - 除了可能满足某人的欲望,以便停止使用它。

var SomeConstructor;

{
    let privateScope = {};

    SomeConstructor = function SomeConstructor () {
        this.someProperty = "foo";
        privateScope.hiddenProperty = "bar";
    }

    SomeConstructor.prototype.showPublic = function () {
        console.log(this.someProperty); // foo
    }

    SomeConstructor.prototype.showPrivate = function () {
        console.log(privateScope.hiddenProperty); // bar
    }

}

var myInstance = new SomeConstructor();

myInstance.showPublic();
myInstance.showPrivate();

console.log(privateScope.hiddenProperty); // error

查看“私人界面模拟”

区块范围

在顶级(功能之外)

var globalVariable = 42;
let blockScopedVariable = 43;

console.log(globalVariable); // 42
console.log(blockScopedVariable); // 43

console.log(this.globalVariable); // 42
console.log(this.blockScopedVariable); // undefined

在一个功能之内

(() => {
  var functionScopedVariable = 42;
  let blockScopedVariable = 43;

  console.log(functionScopedVariable); // 42
  console.log(blockScopedVariable); // 43
})();

console.log(functionScopedVariable); // ReferenceError: functionScopedVariable is not defined
console.log(blockScopedVariable); // ReferenceError: blockScopedVariable is not defined

在一个区块内

{
  var globalVariable = 42;
  let blockScopedVariable = 43;
  console.log(globalVariable); // 42
  console.log(blockScopedVariable); // 43
}

console.log(globalVariable); // 42
console.log(blockScopedVariable); // ReferenceError: blockScopedVariable is not defined

在一个圈子里

用Let in Loops宣言的变量只能在该圈内提到。

for (var i = 0; i < 3; i++) {
  var j = i * 2;
}
console.log(i); // 3
console.log(j); // 4

for (let k = 0; k < 3; k++) {
  let l = k * 2;
}
console.log(typeof k); // undefined
console.log(typeof l); // undefined
// Trying to do console.log(k) or console.log(l) here would throw a ReferenceError.

// Logs 3 thrice, not what we meant.
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}

// Logs 0, 1 and 2, as expected.
for (let j = 0; j < 3; j++) {
  setTimeout(() => console.log(j), 0);
}

临时死区

由于临时死亡区,使用声明的变量在被声明之前无法访问,试图这样做会导致错误。

console.log(noTDZ); // undefined
var noTDZ = 43;
console.log(hasTDZ); // ReferenceError: hasTDZ is not defined
let hasTDZ = 42;

没有重新宣布

var a;
var a; // Works fine.

let b;
let b; // SyntaxError: Identifier 'b' has already been declared

var c;
let c; // SyntaxError: Identifier 'c' has already been declared

格斯特

没有重新分配

const a = 42;
a = 43; // TypeError: Assignment to constant variable.

请注意,这并不意味着值是不可改变的;它的属性仍然可以改变。

const obj = {};
obj.a = 42;
console.log(obj.a); // 42

如果您想要一个不可变的对象,您应该使用 Object.freeze()。

const obj = Object.freeze({a: 40});
obj.a = 42;
console.log(obj.a); // 40
console.log(obj.b); // undefined

初步者需要

在使用 const 表示变量时,您必须始终指定值。

const a; // SyntaxError: Missing initializer in const declaration

这篇文章清楚地定义了 var, let 和 const 的区别。

const 是一个信号,识别器不会被重新分配. 让我们,这是一个信号,变量可以被重新分配, 例如,一个字符在一个旋转, 或一个值交换在一个算法. 它也信号,变量将只在区块它是定义的, 这并不总是整个内容函数. var 现在是最弱的信号可用,当你定义一个变量在 JavaScript。

https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75#.esmkpbg9b

主要差异是范围差异,而让它只能在所宣布的范围内可用,如在圆圈中,可在圆圈之外可访问,例如从MDN的文档(MDN的例子):

function varTest() {
  var x = 1;
  if (true) {
    var x = 2;  // same variable!
    console.log(x);  // 2
  }
  console.log(x);  // 2
}

function letTest() {
  let x = 1;
  if (true) {
    let x = 2;  // different variable
    console.log(x);  // 2
  }
  console.log(x);  // 1
}`

var x = 'global';
let y = 'global';
console.log(this.x); // "global"
console.log(this.y); // undefined

当在区块内使用时,请将变量的范围限制在该区块上。

var a = 1;
var b = 2;

if (a === 1) {
  var a = 11; // the scope is global
  let b = 22; // the scope is inside the if-block

  console.log(a);  // 11
  console.log(b);  // 22
} 

console.log(a); // 11
console.log(b); // 2

差异在于与每一个声明的变量范围。

让变量仅在其最接近的封锁区({... })中可见。让变量仅在变量被宣布后发生的代码线上可用。让变量不被随后的变量或变量重新宣布。让变量不被全球变量添加到全球窗口对象中。让变量易于使用与封锁(它们不会导致赛车条件)。

{
    let x = 1;
}
console.log(`x is ${x}`);  // ReferenceError during parsing: "x is not defined".

{
    x = x + 1;  // ReferenceError during parsing: "x is not defined".
    let x;
    console.log(`x is ${x}`);  // Never runs.
}

没有重新宣言:下列代码表明,被允许宣言的变量不能随后重新宣言:

let x = 1;
let x = 2;  // SyntaxError: Identifier 'x' has already been declared

var button = "I cause accidents because my name is too common.";
let link = "Though my name is common, I am harder to access from other JS files.";
console.log(link);  // OK
console.log(window.link);  // undefined (GOOD!)
console.log(window.button);  // OK

5. 易于使用与关闭: 与 var 表示的变量与关闭内部的关闭工作不太好. 这里是一个简单的旋转,结果的值序列,变量 i 有在不同的时间点:

for (let i = 0; i < 5; i++) {
    console.log(`i is ${i}`), 125/*ms*/);
}

具体而言,这些输出:

i is 0
i is 1
i is 2
i is 3
i is 4

在JavaScript中,我们经常使用变量比它们创建时更晚的时间。当我们通过延迟输出以关闭转移到设置Timeout时:

for (let i = 0; i < 5; i++) {
    setTimeout(_ => console.log(`i is ${i}`), 125/*ms*/);
}

for (var i = 0; i < 5; i++) {
    setTimeout(_ => console.log(`i is ${i}`), 125/*ms*/);
}

i is 5
i is 5
i is 5
i is 5
i is 5

var 是全球范围(可容量)的变量。

Let and const 是区块范围。

测试JS

{ let l = 'let'; const c = 'const'; var v = 'var'; v2 = 'var 2'; } console.log(v, this.v); console.log(v2, this.v2); console.log(l); // ReferenceError: l 未定义 console.log(c); // ReferenceError: c 未定义

让它是 es6的一部分,这些功能将以轻松的方式解释差异。

function varTest() {
  var x = 1;
  if (true) {
    var x = 2;  // same variable!
    console.log(x);  // 2
  }
  console.log(x);  // 2
}

function letTest() {
  let x = 1;
  if (true) {
    let x = 2;  // different variable
    console.log(x);  // 2
  }
  console.log(x);  // 1
}

在 MDN 中查看此链接

let x = 1;

if (x === 1) {
let x = 2;

console.log(x);
// expected output: 2
}

console.log(x);
// expected output: 1

使用Let

允许的关键词将变量声明连接到它所包含的任何区块的范围(通常是 {.. } 对),换句话说,允许随意窃取任何区块的范围为其变量声明。

让变量无法在窗口对象中访问,因为它们无法在全球范围内访问。

function a(){
    { // this is the Max Scope for let variable
        let x = 12;
    }
    console.log(x);
}
a(); // Uncaught ReferenceError: x is not defined

当使用VAR

在 ES5 中, var 和 variables 具有函数中的曲线,这意味着在函数内有效,而不是函数本身之外。

function a(){ // this is the Max Scope for var variable
    { 
        var x = 12;
    }
    console.log(x);
}
a(); // 12

如果你想知道更多,继续阅读下面

最著名的面试问题之一的范围也可能足以准确使用下列;

使用Let

for (let i = 0; i < 10 ; i++) {
    setTimeout(
        function a() {
            console.log(i); //print 0 to 9, that is literally AWW!!!
        }, 
        100 * i);
}

当使用VAR

for (var i = 0; i < 10 ; i++) {
    setTimeout(
        function a() {
            console.log(i); //print 10 times 10
        }, 
        100 * i);
}

这是因为在使用VAR时,对于每个曲线 iteration,变量被分解并共享副本。

如上所述:

差异是分解. var 被分解到最接近的函数区块,然后被分解到最接近的封锁区块,这可能比函数区块小。

例子1:

在我的两个例子中,我有一个功能 myfunc. myfunc 包含一个变量 myvar 等于 10. 在我的第一个例子中,我检查 myvar 等于 10 (myvar==10). 如果是的话,我 agian 宣布一个变量 myvar (现在我有两个 myvar 变量) 使用 var 关键词并将其分配到一个新的值(20)。

此分類上一篇

例2:在我的第二個例子中,而不是在我的條件區域中使用 var 關鍵字,我宣告 myvar 使用 let 關鍵字. 現在,當我呼叫 myfunc 我得到兩個不同的出口: myvar = 20 和 myvar = 10.

因此,差异很简单,即它的范围。

函数 VS 区块范围:

与 var 和 let 的主要区别是,与 var 宣言的变量是函数分解的,而与 let 宣言的函数是区块分解的。

function testVar () {
  if(true) {
    var foo = 'foo';
  }

  console.log(foo);
}

testVar();  
// logs 'foo'


function testLet () {
  if(true) {
    let bar = 'bar';
  }

  console.log(bar);
}

testLet(); 
// reference error
// bar is scoped to the block of the if statement 

当第一个函数测试Var 被称为变量 foo 时,与 var 声明,仍然在 if 声明之外可用。

与Let的变量:

当第二个函数测试Let被称为变量栏,用Let表示,仅可在 if 声明中访问,因为用Let表示的变量是区块分开的(其中一个区块是曲线条之间的代码,例如,如果{},为{},函数{})。

请不要让变量变量:

变量与不要被抓住:

console.log(letVar);

let letVar = 10;
// referenceError, the variable doesn't get hoisted

与 var do 相容的变量:

console.log(varVar);

var varVar = 10;
// logs undefined, the variable gets hoisted

var bar = 5;
let foo  = 10;

console.log(bar); // logs 5
console.log(foo); // logs 10

console.log(window.bar);  
// logs 5, variable added to window object

console.log(window.foo);
// logs undefined, variable not added to window object

我想将这些关键词链接到执行背景,因为执行背景在这一切中都很重要。执行背景有两个阶段:创作阶段和执行阶段。

在创建阶段的执行背景, var, let 和 const 将仍然存储其变量在记忆中与未确定的值在该执行背景的变量环境中. 差异在执行阶段. 如果您使用参考一个变量定义为 var 之前它被分配一个值,它将只是不确定的。

function a(){
    b;
    let b;
}
a();
> Uncaught ReferenceError: b is not defined

const name = 'Max'; let age = 33; var hasHobbies = true; name = 'Maximilian'; age = 34; hasHobbies = false; const summarizeUser = (userName, userAge, userHasHobby) => { return ( 'Name is'+ userName + ', age is'+ userAge +'and the user has hobbies:'+ userHasHobby ); } console.log(summarizeUser(name, age, hasHobbies));

正如你可以从上面的代码运行中看到的那样,当你尝试更改 const 变量时,你会发现一个错误:

试图超越一个“名称”,这是一个恒定的。

TypeError: Invalid assignment to const 'name'.

但是,看看放变量。

首先,我们宣布让年龄=33岁,然后将另一个值年龄=34岁,这是OK;当我们试图改变时,我们没有任何错误。

正如我目前正在试图深入了解JavaScript,我将分享我的简短研究,其中包含一些已经讨论的伟大作品,以及一些其他细节,从不同的角度。

理解VAR和LAT之间的差异可以更容易,如果我们理解函数和区块范围之间的差异。

让我们来看看以下案例:

(function timer() {
    for(var i = 0; i <= 5; i++) {
        setTimeout(function notime() { console.log(i); }, i * 1000);
    }
})();


   Stack            VariableEnvironment //one VariablEnvironment for timer();
                                       // when the timer is out - the value will be the same for each iteration
5. [setTimeout, i]  [i=5] 
4. [setTimeout, i]  
3. [setTimeout, i]
2. [setTimeout, i]
1. [setTimeout, i]
0. [setTimeout, i]

####################    

(function timer() {
    for (let i = 0; i <= 5; i++) {
        setTimeout(function notime() { console.log(i); }, i * 1000);
    }
})();

   Stack           LexicalEnvironment - each iteration has a new lexical environment
5. [setTimeout, i]  [i=5]       
                      LexicalEnvironment 
4. [setTimeout, i]    [i=4]     
                        LexicalEnvironment 
3. [setTimeout, i]      [i=3]       
                         LexicalEnvironment 
2. [setTimeout, i]       [i=2]
                           LexicalEnvironment 
1. [setTimeout, i]         [i=1]
                             LexicalEnvironment 
0. [setTimeout, i]           [i=0]

当按时()被称为执行内容时,将创建一个内容,该内容将包含每个字符串的变量环境和所有相应的语法环境。

更简单的例子

功能范围

function test() {
    for(var z = 0; z < 69; z++) {
        //todo
    }
    //z is visible outside the loop
}

区块范围

function test() {
    for(let z = 0; z < 69; z++) {
        //todo
    }
    //z is not defined :(
}

简而言之,Let和Var之间的区别在于Var是功能分解,Let是区块分解。

答答答答答答答答答答答答答答答答答

var 变量是全球性的,基本上可以到达到任何地方,而让变量不是全球性的,只有直到一个关闭的偏见杀死它们。

请参见下面的我的例子,并注意狮子(Let)变量如何在两个 console.logs 中以不同的方式行事;它在第二个 console.log 中变得无效。

var cat = "cat";
let dog = "dog";

var animals = () => {
    var giraffe = "giraffe";
    let lion = "lion";

    console.log(cat);  //will print 'cat'.
    console.log(dog);  //will print 'dog', because dog was declared outside this function (like var cat).

    console.log(giraffe); //will print 'giraffe'.
    console.log(lion); //will print 'lion', as lion is within scope.
}

console.log(giraffe); //will print 'giraffe', as giraffe is a global variable (var).
console.log(lion); //will print UNDEFINED, as lion is a 'let' variable and is now out of scope.

msg = “Hello World” 函数 doWork() { // msg 将是可用的,因为它被定义在这个开幕式上! 让朋友 = 0; console.log(msg); // 与 VAR 虽然: for (var iCount2 = 0; iCount2 < 5; iCount2++) {} // iCount2 将在这个开幕式后可用! console.log(iCount2); for (let iCount1 = 0; iCount1 < 5; iCount1++) {} // iCount1 将没有

下面表明“让我们”和“存在”在范围内是如何不同的:

let gfoo = 123;
if (true) {
    let gfoo = 456;
}
console.log(gfoo); // 123

var hfoo = 123;
if (true) {
    var hfoo = 456;
}
console.log(hfoo); // 456

gfoo,定义为 let 最初是在全球范围内,当我们宣布 gfoo 再次在如果条款的范围改变,当一个新的值被分配到变量在该范围内,它不会影响全球范围。

虽然 hfoo,由 var 定义,起初在全球范围内,但再次当我们在 if 条款内宣布它时,它考虑到全球范围 hfoo,尽管 var 已再次被用来宣布它。

ES6 引入了两个新的关键字(let 和 const) 替代到 var。

当你需要一个区块水平下降时,你可以用Let和Const而不是VAR去。

下面的表总结了 var, let 和 const 之间的差异

此分類上一篇

在基本上,

for (let i = 0; i < 5; i++) {
  // i accessible ✔️
}
// i not accessible ❌

for (var i = 0; i < 5; i++) {
  // i accessible ✔️
}
// i accessible ✔️

<unk>️ Sandbox 要玩 ↓

此分類上一篇

我刚刚遇到了一个使用案例,我不得不使用Var over让介绍新的变量。

我想创建一个新的变量,具有动态变量名称。

let variableName = 'a';
eval("let " + variableName + '= 10;');
console.log(a);   // this doesn't work
var variableName = 'a';
eval("var " + variableName + '= 10;');
console.log(a);   // this works

上面的代码不起作用,因为 eval 引入一个新的代码区块. 使用 var 的声明将声明这个代码区块之外的变量,因为 var 声明函数范围内的变量。

另一方面,让我们在区块范围内宣布一个变量,因此,一个变量仅在 eval 区块中可见。

在2015年之前,使用 var 关键字是宣布 JavaScript 变量的唯一方式。

在 ES6 (JavaScript 版本) 之后,它允许 2 个新的关键字 let & const。

let = 可以重新分配 const = 不能重新分配 const ( const 源于常态,短形的“const” )

例子:

假设,宣布一个国家名称 / 你的母亲名称, const 是最合适的这里. 因为有更少的机会改变一个国家名称或你的母亲名称很快或晚些时候. 你的年龄,体重,工资,自行车的速度和更多类似于这些类型的数据,经常改变或需要重新分配。

这个解释是从我在Medium上写的一篇文章中得出的:

Hoisting 是一个 JavaScript 机制,在其中变量和函数声明被转移到其范围的顶部,由分数者将源代码列入一个中间代表性之前,实际的代码执行由 JavaScript 解释器开始。

var   --> Function scope  
let   --> Block scope
const --> Block scope

是的

在此样本中,你可以看到我被宣布在一个如果区块. 但它被宣布使用 var. 因此,它获得功能范围. 它意味着你仍然可以访问变量 i 内部函数 x. 因为 var 总是被推到函数. 尽管变量 i 被宣布在一个如果区块, 因为它使用 var 它被推到主函数 x。

函数 x(){ if(true){ var i = 100; } console.log(i); } x();

现在变量 i 被宣布在函数 y. 因此, i 被定义为函数 y. 您可以访问 i 内部函数 y. 但不是从外部函数 y。

let, const

让和 const 有区块范围。

但是,差异是,当你将值分配给 const 时,你不能再分配。

console.log(x); var x = 100;

console.log(x); // ERROR let x = 100;

“var”是函数分解,而“let”是区块分解。

您可以在函数中的任何地方使用变量,然后在函数中的任何地方使用变量,然后在函数中的任何地方使用变量。

或者你可以只是使用 Var 整个时间,因为你很不可能在一个函数内部发生范围冲突,然后你不需要跟踪你定义为允许或变量的变量。

有些人建议使用让所有时间,但这不是我的偏好,因为在许多其他编程语言的本地变量是功能的破坏,如果你使用其他,那么你可能会发现它更容易思考这个模式整个时间,而不是在使用JavaScript时更换。