每一次標準的誕生意味着語言的完善,功能的增強,javascript自己也有一些使人不滿意的地方javascript
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>let聲明的變量具備塊級做用域</title> </head> <body> </body> <script> if (true) { let a = 20; console.log(a); //20 if (true) { let b = 50; console.log(b)//50 } } console.log(a) //a is not define </script> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>let能夠防止循環變量變成全局變量</title> </head> <body> </body> <script> for(let i =0;i<2;i++){ } console.log(i) //i is not define </script> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>let聲明的變量不會進行變量提高</title> </head> <body> </body> <script> console.log(a) // a is not define let a = 20; </script> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>let聲明的變量具備暫存性死區的特性</title> </head> <body> </body> <script> let a = 20; if(true) { console.log(a) let a = 30; } </script> </html>
此題的關鍵點:變量i是全局的 函數輸出的值是全局做用域下的i
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>let面試題</title> </head> <body> </body> <script> var arr = []; for(var i = 0;i<2;i++){ arr[i] = function () { console.log(i) } } arr[0]()//2 arr[1]()//2 </script> </html>
關鍵點:函數執行的時候,輸出的是上一級循環產生的塊狀做用域下i的值html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>let面試題</title> </head> <body> </body> <script> let arr = []; for(let i =0;i<2;i++){ arr[i]= function () { console.log(i) } } arr[0]()//0 arr[1]()//1 </script> </html>
const用來聲明常量 常量就是值 (內存地址)不能變化的量
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>const聲明的常量具備塊級做用域的特性</title> </head> <body> </body> <script> if(true){ const a = 10; if(true) { const a =20; console.log(a)//20 } console.log(a)//10 } console.log(a)// a is not define </script> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>const聲明的常量必須賦初始值</title> </head> <body> </body> <script> const a; console.log(a) </script> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>const聲明的常量值不能更改</title> </head> <body> </body> <script> const arr = [200,300]; arr[0]='hello'; arr[1]='word'; console.log(arr);//['hello','word'] arr = [200,500]; console.log(arr) //TypeError: invalid assignment to const `arr' </script> </html>