8個(gè)JavaScript中常遇到的坑
JavaScript默認(rèn)使用字典序(alphanumeric)來排序。因此, [1,2,5,10].sort() 的結(jié)果是 [1, 10, 2, 5] 。
如果你想正確的排序,應(yīng)該這樣做: [1,2,5,10].sort((a, b) => a - b)
2. new Date() 十分好用new Date()的使用方法有:
不接收任何參數(shù):返回當(dāng)前時(shí)間;
接收一個(gè)參數(shù)x: 返回1970年1月1日 + x毫秒的值。
new Date(1, 1, 1)返回1901年2月1號(hào)。
然而....,new Date(2016, 1, 1)不會(huì)在1900年的基礎(chǔ)上加2016,而只是表示2016年。
3. 替換函數(shù)沒有真的替換?let s = 'bob'const replaced = s.replace(’b’, ’l’)replaced === 'lob' // 只會(huì)替換掉第一個(gè)bs === 'bob' // 并且s的值不會(huì)變
如果你想把所有的b都替換掉,要使用正則:
'bob'.replace(/b/g, ’l’) === ’lol’ 4. 謹(jǐn)慎對(duì)待比較運(yùn)算
// 這些可以’abc’ === ’abc’ // true1 === 1 // true// 然而這些不行[1,2,3] === [1,2,3] // false{a: 1} === {a: 1} // false{} === {} // false
因?yàn)閇1,2,3]和[1,2,3]是兩個(gè)不同的數(shù)組,只是它們的元素碰巧相同。因此,不能簡單的通過===來判斷。
5. 數(shù)組不是基礎(chǔ)類型typeof {} === ’object’ // truetypeof ’a’ === ’string’ // truetypeof 1 === number // true// 但是....typeof [] === ’object’ // true
如果要判斷一個(gè)變量var是否是數(shù)組,你需要使用 Array.isArray(var) 。
6. 閉包這是一個(gè)經(jīng)典的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,...,然而實(shí)際上卻不會(huì)。知道如何Debug嘛? 有兩種方法:
a.使用let而不是var。
b.使用bind函數(shù)。
Greeters.push(console.log.bind(null, i))
當(dāng)然,還有很多解法。這兩種是我最喜歡的!
7. 關(guān)于bind下面這段代碼會(huì)輸出什么結(jié)果?
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()
如果你說程序會(huì)崩潰,并且報(bào)錯(cuò):Cannot read property ’name’ of undefined。 因?yàn)間reet沒有在正確的環(huán)境下執(zhí)行。當(dāng)然,也有很多方法解決這個(gè)BUG!
我喜歡使用bind函數(shù)來解決問題:
asyncGreet () { this.someThingAsync() .then(this.greet.bind(this))}
這樣會(huì)確保greet會(huì)被Foo的實(shí)例調(diào)用,而不是局部的函數(shù)的this。
如果你想要greet永遠(yuǎn)不會(huì)綁定到錯(cuò)誤的作用域,你可以在構(gòu)造函數(shù)里面使用bind來綁 。
class Foo { constructor (name) { this.name = name this.greet = this.greet.bind(this) }}
你也可以使用箭頭函數(shù)(=>)來防止作用域被修改。備注:可以參考Fundebug的另一篇博客 JavaScript初學(xué)者必看“箭頭函數(shù)”。
asyncGreet () { this.someThingAsync() .then(() => { this.greet() })} 8. Math.min()比Math.max()大
Math.min() < Math.max() // false
因?yàn)镸ath.min() 返回 Infinity, 而 Math.max()返回 -Infinity。
來自:http://www.helloweba.com/view-blog-430.html
相關(guān)文章:
1. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向2. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明3. CSS hack用法案例詳解4. PHP設(shè)計(jì)模式中工廠模式深入詳解5. 用css截取字符的幾種方法詳解(css排版隱藏溢出文本)6. ASP+ajax實(shí)現(xiàn)頂一下、踩一下同支持與反對(duì)的實(shí)現(xiàn)代碼7. .NET中l(wèi)ambda表達(dá)式合并問題及解決方法8. ThinkPHP5實(shí)現(xiàn)JWT Token認(rèn)證的過程(親測(cè)可用)9. asp中response.write("中文")或者js中文亂碼問題10. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析
