(编辑:jimmy 日期: 2024/11/18 浏览:2)
本文实例讲述了ES6 let和const定义变量与常量的应用。分享给大家供大家参考,具体如下:
关于 let
{ var a = 12; let b = 15; { console.log(a); // 12 console.log(b); // 15 } }
console.log(a); // Uncaught ReferenceError: a is not defined,直接报错 let a = 12; // let定义的变量不能进行变量的提升
console.log(b); // undefined var b = 12; // 上面的过程存在变量提升过程如下: /* var b; console.log(b); b = 12; */
{ var a = 12; let b = 15; console.log(b); // 15 } console.log(a); // 12 console.log(b); // Uncaught ReferenceError: b is not defined
for(var i=0;i<5;i++) {} console.log(i); // 5 for(let m=0;m<5;m++){} console.log(m); // Uncaught ReferenceError: m is not defined
var a = 18; var b = 10; fun(); function fun(){ console.log(b); // 10 console.log(a); // Uncaught ReferenceError: a is not defined let a; }
let a; var a; // Uncaught SyntaxError: Identifier 'a' has already been declared
var config = (function () { var res = []; res.push(1); res.push(2); res.push(3); return res; })(); console.log(config); // [1,2,3]
let config; { config = []; config.push(1); config.push(2); config.push(3); } console.log(config); // [1,2,3]
'use strict'; function a(){console.log(1);} (function () { a(); // 去除'use strict' 之后 报错:a is not a function,加上'use strict'之后正常,输出1 if(false) { function a(){console.log(2);} // 此处重新声明和赋值了一个a函数,上面输出1的时候表示没有被提升 } })();
var arr = []; for(var i=0;i<5;i++) { arr.push(function () { console.log(i); }) } arr[1](); // 5
var arr = []; for(var i=0;i<5;i++) { arr.push((function (i) { return function () { console.log(i); } })(i)); } arr[1](); // 1
var arr = []; for(let i=0;i<5;i++) { arr.push(function () { console.log(i); }) } arr[1](); // 1
关于 const
const a = { name:'J' }; a.name = 'Z'; a.age = 10; console.log(a); // {name: "Z", age: 10} a = {}; // 尝试修改引用的地址 console.log(a); // Uncaught TypeError: Assignment to constant variable.
const a = { name:'K' } a.age = 13; console.log(a); // {name: "K", age: 13} Object.freeze(a); a.age = 14; console.log(a); // Uncaught TypeError: Cannot assign to read only property 'age' of object '#<Object>'
更多关于JavaScript相关内容可查看本站专题:《javascript面向对象入门教程》、《JavaScript查找算法技巧总结》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》
希望本文所述对大家JavaScript程序设计有所帮助。