1.let是块级作用域,函数内部使用let定义后,对函数外部无影响。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>let</title> </head> <body> <script> function test() { for (let index = 0; index < 3; index++) { console.log(index)//0,1,2 } console.log(index)//index is not defined } test();//执行test函数 </script> </body> </html>
2.const定义的变量不可以修改,必须定义变量的时候就赋值
const只定义常量吗???
3.var定义的变量可以修改,如果不初始化会输出undefined,不会报错。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>let</title> </head> <body> <script> function test() { for (var index = 0; index < 3; index++) { console.log(index)//0,1,2 } console.log(index)//3 } test();//执行test函数 </script> </body> </html>