前言
這里我們針對JavaScript初學者給出一些技巧和列出一些陷阱。如果你已經是一個磚家,也可以讀一讀。
1. 你是否嘗試過對數組元素進行排序?
JavaScript默認使用字典序(alphanumeric)來排序。因此, [1,2,5,10].sort()的結果是[1, 10, 2, 5]。
如果你想正確的排序,應該這樣做: [1,2,5,10].sort((a, b) => a - b)
2. new Date() 十分好用
new Date()可以接收:
`new Date(2016, 1, 1)`不會在1900年的基礎上加2016,而只是表示2016年。3. 替換函數沒有真的替換?
let s = "bob"const replaced = s.replace('b', 'l')replaced === "lob" // 只會替換掉第一個bs === "bob" // 并且s的值不會變如果你想把所有的b都替換掉,要使用正則:
"bob".replace(/b/g, 'l') === 'lol'
4. 謹慎對待比較運算
// 這些可以'abc' === 'abc' // true1 === 1 // true// 然而這些不行[1,2,3] === [1,2,3] // false{a: 1} === {a: 1} // false{} === {} // false因為[1,2,3]和[1,2,3]是兩個不同的數組,只是它們的元素碰巧相同。因此,不能簡單的通過`===`來判斷。
5. 數組不是基礎類型
typeof {} === 'object' // truetypeof 'a' === 'string' // truetypeof 1 === number // true// 但是....typeof [] === 'object' // true如果要判斷一個變量`var`是否是數組,你需要使用`Array.isArray(var)` 。
6. 閉包
這是一個經典的JavaScript面試題:
const Greeters = []for (var i = 0 ; i < 10 ; i++) { Greeters.push(function () { return console.log(i) })}Greeters[0]() // 10Greeters[1]() // 10Greeters[2]() // 10雖然期望輸出0,1,2,...,然而實際上卻不會。知道如何Debug嘛?
有兩種方法:
- 使用`let`而不是`var`。 (備注:可以參考這篇文章 //m.survivalescaperooms.com/article/117343.htm) - 使用`bind`函數。(備注:可以參考這篇文章 //m.survivalescaperooms.com/article/115323.htm)Greeters.push(console.log.bind(null, i))
當然,還有很多解法。這兩種是我最喜歡的!
7. 關于bind
下面這段代碼會輸出什么結果?
class Foo { constructor (name) { this.name = name } greet () { console.log('hello, this is ', this.name) } someThingAsync () { return Promise.resolve() } asyncGreet () { this.someThingAsync() .then(this.greet) }}new Foo('dog').asyncGreet()如果你說程序會崩潰,并且報錯:Cannot read property 'name' of undefined
新聞熱點
疑難解答
圖片精選