第一章中做者介紹了各類值,可是這些獨立的值是沒有意義的,只有當值放在更大的框架的時候纔會彰顯它們的價值。因此第二章開始介紹程序結構。javascript
一、var VS. let 以及 consthtml
做者推薦用 let ,由於var 有一些稀奇古怪的行爲?暫時沒有詳細解釋。java
const 用於綁定常量值瀏覽器
二、關於 JavaScript 的運行環境框架
在運行 JavaScript 程序的環境中,並不單單隻有你定義的綁定,還有其它各式各樣初始化就有的「環境綁定」。ide
例如說 prompt , 這是一個持有函數類型的綁定,不過在現代瀏覽器裏幾乎不用了,理由是它無法裝飾。。不過在玩具式程序裏卻是用得不少。函數
typeof prompt "function"
typeof NaN "number"
三、關於自增號。this
在 JavaScript 裏 ++ -- += -= *= 都是能夠用的,可是在 Python 裏不行,它有 += 卻沒有 ++ -- spa
四、javascript 命名規範.net
遵循駝峯命名法(能夠發現 JavaScript 標準函數就是那樣命名的, 但爲何像 Number 那樣的函數第一個字母是大寫呢?由於是它是構造器)
Number("xxxx") NaN Number("222") 222
五、打印下面這個圖形:
# ## ### #### ##### ###### #######
let result = "#"; for (let i = 0; i != 7; ++i) { console.log(result); result += "#"; }
六、關於控制流的小練習
Write a program that uses console.log
to print all the numbers from 1 to 100, with two exceptions. For numbers divisible by 3, print "Fizz"
instead of the number, and for numbers divisible by 5 (and not 3), print "Buzz"
instead.
When you have that working, modify your program to print "FizzBuzz"
for numbers that are divisible by both 3 and 5 (and still print "Fizz"
or "Buzz"
for numbers divisible by only one of those).
<script type="text/javascript"> for (let i = 1; i <= 100; ++i) { if (i % 3 === 0 && i % 5 === 0) { console.log("FizzBuzz"); } else if (i % 5 === 0) { console.log("Buzz"); } else if (i % 3 === 0) { console.log("Fizz"); } else { console.log(i); } } </script>
PS. 優先級 + - 等遠大於 == != 遠大於 &&和||(其中 && 大於||) 賦值號優先級是最小的,另外,上面的 === 屬於畫蛇添足,當能夠肯定兩邊值類型相同的時候用 == 就能夠了。
七、練習三:
Passing this string to console.log
should show something like this:
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
When you have a program that generates this pattern, define a binding size = 8
and change the program so that it works for any size
, outputting a grid of the given width and height.
<script type="text/javascript"> let size = Number(prompt("Enter the size of chessboard")); if (!Number.isNaN(size)) { // NaN 雖然含義是 "Not a Number",不過 typeof 輸出類型仍然是 Number // 另外,意外發現 IE 環境竟然不支持 isNaN 屬性 let result = ""; for (let i = 0; i != size; ++i) { for (let j = 0; j != size; ++j) { if ((i + j) % 2 == 0) { result += " "; } else { result += "#"; } } result += "\n"; } console.log(result); } </script>