ES6--let声明变量
1.块作用域
<!--
* @Author: RealRoad
* @Date: 2023-05-31 14:33:10
* @LastEditors: Mei
* @LastEditTime: 2023-05-31 14:42:09
* @FilePath: \vscode\ECMA\01\01.html
* @Description:
*
* Copyright (c) 2023 by ${git_name_email}, All Rights Reserved.
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul>
<li>111</li>
<li>222</li>
<li>333</li>
</ul>
<script>
// {//块级作用域
// let i=100;
// }
// console.log(i)
// for(let i=0;i<5;i++){
// }
// console.log(i)
var oli=document.querySelectorAll("ul li")
for(let i=0;i<oli.length;i++){
oli[i].onclick=function(){
console.log(i)
}
}
</script>
</body>
</html>
2.不允许重复声明
3.变量提升
暂存性死区
4.不与顶层对象挂钩
<!--
* @Author: RealRoad
* @Date: 2023-05-31 14:42:43
* @LastEditors: Mei
* @LastEditTime: 2023-05-31 14:52:25
* @FilePath: \vscode\ECMA\01\02.html
* @Description:
*
* Copyright (c) 2023 by ${git_name_email}, All Rights Reserved.
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//不允许重复声明
var a=1;
// let a=2;
console.log(a)
//3-变量提升
//暂存性死区
// console.log(myname)
let myname="mez"
// let myname="mez" 报错
function test(){
let myname="kunkun"
console.log(myname)
}
test()
//4.不与顶层对象挂钩
// let myage=100 //undefined
var myage=100
console.log(window.myage)
</script>
</body>
</html>
ES6--const声明变量
const声明的为常量,拥有以下特性:
1.常量
2.不能重复定义
3.块级作用域
4.暂存性死区,声明不提升
5.不与顶层对象挂钩
还有需要注意的点:所有的const声明都不能被修改吗?
答:const声明的对象不能被修改,如const obj={name:"test1"} 修改成const obj="test2"会报错。
但是对象里面的属性可以修改,如obj.name="kunkun".
<!--
* @Author: RealRoad
* @Date: 2023-05-31 14:55:04
* @LastEditors: Mei
* @LastEditTime: 2023-05-31 15:09:25
* @FilePath: \vscode\ECMA\02\1.html
* @Description:
*
* Copyright (c) 2023 by ${git_name_email}, All Rights Reserved.
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//1.常量
const myname="mez"
// myname="kunkun" 报错
// const myname2; 报错 ,必须在初始化赋值
//2.不能重复定义
// const myname="kunkun"
//3.块级作用域
{
const myname2="Ikun"
}
// console.log(myname2) 报错
//4.暂存性死区,声明不提升
const myname3="mez"
function test(){
const myname3="kunkun"
console.log(myname3)
}
test()
//5.不与顶层对象挂钩
const myage=100
// console.log(window.myage) undefined
const myobj={
name:"rap",
age:100
}
//myobj ="test" 报错
myobj.name="ji哥"
console.log(myobj)
//freeze 不让修改对象
const myobj2=Object.freeze({
name:"chang",
age:2.5
})
myobj2.name="test2"
console.log(myobj2)
</script>
</body>
</html>
那么,如果让对象里面的内容也不能修改呢?
答:可以使用freeze()方法,使用Object.freeze({...})定义的对象不能够修改。