這裡dbestech針對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()
的使用方法有:
- 不接收任何參數:傳回目前時間;
- 接收一個參數
: 傳回1970年1月1日 +x
毫秒的值。x
-
傳回1901年2月1号。new Date(1, 1, 1)
- 然而….,
不會在1900年的基礎上加2016,而隻是表示2016年。new Date(2016, 1, 1)
3. 替換函數沒有真的替換?
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' // true
1 === 1 // true
// 然而這些不行
[1,2,3] === [1,2,3] // false
{a: 1} === {a: 1} // false
{} === {} // false
因為[1,2,3]和[1,2,3]是兩個不同的數組,隻是它們的元素碰巧相同。是以,不能簡單的通過
===
來判斷。·
5. 數組不是基礎類型
typeof {} === 'object' // true
typeof 'a' === 'string' // true
typeof 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]() // 10
Greeters[1]() // 10
Greeters[2]() // 10
雖然期望輸出0,1,2,…,然而實際上卻不會。知道如何Debug嘛?
有兩種方法:
- 使用
而不是let
。備注:可以參考Fundebug的另一篇部落格 ES6之”let”能替代”var”嗎?var
- 使用
函數。備注:可以參考Fundebug的另一篇部落格 JavaScript初學者必看“this”bind
當然,還有很多解法。這兩種是我最喜歡的!Greeters.push(console.log.bind(null, i))
7. 關于 bind
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。
1、因為第16行的
geet
沒有在正确的環境下執行。當然,也有很多方法解決這個BUG!
我喜歡使用
bind
函數來解決問題:
asyncGreet () {
this.someThingAsync()
.then(this.greet.bind(this))
}
這樣會確定
greet
會被Foo的執行個體調用,而不是局部的函數的
this
。
2、如果你想要
greet
永遠不會綁定到錯誤的作用域,你可以在構造函數裡面使用
bind
來綁 。
//code from http://caibaojian.com/8-javascript-attention.html
class Foo {
constructor(name) {
this.name = name this.greet = this.greet.bind(this)
}
}
3、你也可以使用箭頭函數(=>)來防止作用域被修改。備注:可以參考Fundebug的另一篇部落格 JavaScript初學者必看“箭頭函數”。
asyncGreet() {
this.someThingAsync().then(() = >{
this.greet()
})
}
8. Math.min()比Math.max()大
Math.min() < Math.max() // false
因為Math.min() 傳回 Infinity, 而 Math.max()傳回 -Infinity。
轉載于:https://www.cnblogs.com/ChinaLife/p/7121440.html