1. 你是否嘗試過對數(shù)組元素進行排序?
JavaScript
默認使用字典序
(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ù):返回當前時間;
-
接收一個參數(shù)
`x`:
返回
1970
年
1
月
1
日
+ `x`
毫秒的值。
- `new Date(1, 1, 1)`
返回
1901
年
2
月
1
號。
-
然而
....
,
`new Date(2016, 1, 1)`
不會在
1900
年的基礎(chǔ)上加
2016
,而只是表示
2016
年。
3. 替換函數(shù)沒有真的替換?
let s = "bob"
const replaced = s.replace('b', 'l')
replaced === "lob" //
只會替換掉第一個
b
s === "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]
是兩個不同的數(shù)組,只是它們的元素碰巧相同。因此,不能簡單的通過
`===`
來判斷。
5. 數(shù)組不是基礎(chǔ)類型
typeof {} === 'object' // true
typeof 'a' === 'string' // true
typeof 1 === number // true//
但是
....
typeof [] === 'object' // true
如果要判斷一個變量`var`
是否是數(shù)組,你需要使用
`Array.isArray(var)`
。
6. 閉包
這是一個經(jīng)典的JavaScript
面試題:
const Greeters = []
for (
var i = 0 ; i < 10 ; i++) {
Greeters.push(
function (){
return console.log(i) })
}
Greeters[0]() // 10
Greeters[1]() // 10
Greeters[2]() // 10
雖然期望輸出0,1,2,...
,然而實際上卻不會。知道如何
Debug
嘛? 有兩種方法:
-
使用
`let`
而不是
`var`
。備注:可以參考
Fundebug
的另一篇博客
[ES6
之
"let"
能替代
"var"
嗎
?](https://blog.fundebug.com/2017/05/04/why-you-should-not-use-var/) -
使用
`bind`
函數(shù)。備注:可以參考
Fundebug
的另一篇博客
[JavaScript
初學(xué)者必看
“this”](https://blog.fundebug.com/2017/05/17/javascript-this-for-beginners/)
Greeters.push(
console.log.bind(
null,
i))
當然,還有很多解法。這兩種是我最喜歡的!
7. 關(guān)于 bind
下面這段代碼會輸出什么結(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()
如果你說程序會崩潰,并且報錯:Cannot read property 'name' of undefined
。 因為第
16
行的
`geet`
沒有在正確的環(huán)境下執(zhí)行。當然,也有很多方法解決這個
BUG
!
-
我喜歡使用
`bind`
函數(shù)來解決問題:
asyncGreet () {
this.someThingAsync()
.then(
this.greet.bind(
this))
}
這樣會確保`greet`
會被
Foo
的實例調(diào)用,而不是局部的函數(shù)的
`this`
。
-
如果你想要
`greet`
永遠不會綁定到錯誤的作用域,你可以在構(gòu)造函數(shù)里面使用
`bind`
來綁定。
class
Foo{
constructor (name) {
this.name = name
this.greet =
this.greet.bind(
this)
}
}
-
你也可以使用箭頭函數(shù)
(=>)
來防止作用域被修改。備注:可以參考
Fundebug
的另一篇博客
[JavaScript
初學(xué)者必看
“
箭頭函數(shù)
”](https://blog.fundebug.com/2017/05/25/arrow-function-for-beginner/)
。
asyncGreet () {
this.someThingAsync()
.
then(() => {
this.greet()
})
}
8. Math.min()比Math.max()大
Math.min() < Math.max() // false
因為Math.min()
返回
Infinity,
而
Math.max()
返回
-Infinity
。
來源:Fundebug
博客