JavaScript中8個常見的陷阱

譯者按: 漫漫編程路,總有一些坑讓你淚流滿面。javascript

原文: Who said javascript was easy ?java

譯者: Fundebug面試

爲了保證可讀性,本文采用意譯而非直譯。另外,本文版權歸原做者全部,翻譯僅用於學習編程

這裏咱們針對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()能夠接收: - 不接收任何參數:返回當前時間; - 接收一個參數x: 返回1970年1月1日 + x毫秒的值。 - new Date(1, 1, 1)返回1901年2月1號。 - 然而....,new Date(2016, 1, 1)不會在1900年的基礎上加2016,而只是表示2016年。微信

3. 替換函數沒有真的替換?

```js
let s = "bob"
const replaced = s.replace('b', 'l')
replaced === "lob" // 只會替換掉第一個b
s === "bob" // 而且s的值不會變
```

若是你想把全部的b都替換掉,要使用正則:
```js
"bob".replace(/b/g, 'l') === 'lol'
```

4. 謹慎對待比較運算

```js
// 這些能夠
'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. 數組不是基礎類型

```js
typeof {} === 'object'  // true
typeof 'a' === 'string' // true
typeof 1 === number     // true
// 可是....
typeof [] === 'object'  // true
```
若是要判斷一個變量`var`是不是數組,你須要使用`Array.isArray(var)`。

6. 閉包

這是一個經典的JavaScript面試題:
```js
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`函數。備註:能夠參考Fundebug的另外一篇博客[JavaScript初學者必看「this」](https://blog.fundebug.com/2017/05/17/javascript-this-for-beginners/)
  ```js
  Greeters.push(console.log.bind(null, i))
  ```
固然,還有不少解法。這兩種是我最喜歡的!

7. 關於bind

下面這段代碼會輸出什麼結果?
```js
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`沒有在正確的環境下執行。固然,也有不少方法解決這個BUG!

- 我喜歡使用`bind`函數來解決問題:
	```js
	asyncGreet () {
	  this.someThingAsync()
	  .then(this.greet.bind(this))
	}
	```

	這樣會確保`greet`會被Foo的實例調用,而不是局部的函數的`this`。
- 若是你想要`greet`永遠不會綁定到錯誤的做用域,你能夠在構造函數裏面使用`bind`來綁定。
	```js
	class Foo {
	  constructor (name) {
	    this.name = name
	    this.greet = this.greet.bind(this)
	  }
	}
	```

- 你也可使用箭頭函數(=>)來防止做用域被修改。備註:能夠參考Fundebug的另外一篇博客[JavaScript初學者必看「箭頭函數」](https://blog.fundebug.com/2017/05/25/arrow-function-for-beginner/)。
	```js
	asyncGreet () {
	  this.someThingAsync()
	  .then(() => {
	    this.greet()
	  })
	}
	```

8. Math.min()比Math.max()大

```js
Math.min() < Math.max() // false
```
由於Math.min() 返回 Infinity, 而 Math.max()返回 -Infinity。

###關於Fundebug閉包

Fundebug專一於JavaScript、微信小程序、微信小遊戲、支付寶小程序、React Native、Node.js和Java實時BUG監控。 自從2016年雙十一正式上線,Fundebug累計處理了7億+錯誤事件,獲得了Google、360、金山軟件、百姓網等衆多知名用戶的承認。歡迎免費試用!async

版權聲明

轉載時請註明做者Fundebug以及本文地址: https://blog.fundebug.com/2017/06/28/who-said-js-was-easy/

相關文章
相關標籤/搜索