誰說Javascript簡單的?

誰說Javascript簡單的? – Hacker Noon

原文連接
 

這裏有一些 Javascript初學者應該知道的技巧和陷阱。若是你已是專家了,順便溫習一下。javascript

Javascript也只不過是一種編程語言。怎麼可能出錯嘛?html

1. 你有沒有嘗試給一組數字排序?

Javascript 的sort()函數在默認狀況下使用字母數字(字符串Unicode碼點)排序。java

因此[1,2,5,10].sort() 會輸出 [1, 10, 2, 5].面試

要正確的排序一個數組, 你能夠用 [1,2,5,10].sort((a, b) => a — b)正則表達式

很簡單的解決方案, 前提是你得知道有這麼個坑 :)編程

2. new Date() 很棒

new Date() 能夠接受:api

  • 沒有參數: 返回當前時間數組

  • 一個參數 x: 返回1970年1月1日 + x 毫秒。 瞭解 Unix 的人知道爲何。markdown

  • new Date(1, 1, 1) 返回 1901, 二月 , 1號\。由於,第一個參數表示1900年加1年,第二個參數表示這一年的第二個月(所以是二月) — 腦回路正常的人會從1開始索引 — ,第三個參數很明顯是這個月的第一天,因此1 — 有時候索引確實從1開始 — 。閉包

  • new Date(2016, 1, 1) 不會給1900年加上2016。它僅表明2016年。

3. Replace 並不「替代」

let s = "bob"
const replaced = s.replace('b', 'l')
replaced === "lob"
s === "bob"

我以爲這是一件好事,由於我不喜歡函數改變它們的輸入。 你還應該知道 replace 只會替換第一個匹配的字符串:

若是你想替換全部匹配的字符串,你能夠使用帶/g標誌的正則表達式 :

"bob".replace(/b/g, 'l') === 'lol' // 替換全部匹配的字符串

4. 比較的時候要注意

// These are ok
'abc' === 'abc' // true
1 === 1         // true
// These are not
[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
// But....
typeof [] === 'object'  // true

若是你想知道你的變量是否是數組,你仍然能夠用Array.isArray(myVar)

6. 閉包

這是一個頗有名的面試題:

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… ? 你知道它爲何不是這樣輸出的嗎? 你會怎樣修改讓它輸出 0, 1, 2… ?

這裏有兩種可能的解決方法:

  • 用 let 替代 var. Boom. 解決了.

letvar的不一樣在於做用域。var的做用域是最近的函數塊,let的做用域是最近的封閉塊,封閉塊能夠小於函數塊(若是不在任何塊中,則letvar都是全局的)。(來源

  • 替代方法: 用 bind:
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,給你一分。

緣由: greet 沒有在正確的上下文中運行。一樣,這個問題依然有不少解決方案。

  • 我我的喜歡
    asyncGreet () {
    this.someThingAsync()
    .then(this.greet.bind(this))
    }

這樣能夠確保類的實例做爲上下文調用greet

  • 若是你認爲greet 不該該在實例上下文以外運行, 你能夠在類的constructor中綁定它:

    class Foo {
    constructor (name) {
    this.name = name
    this.greet = this.greet.bind(this)
    }
    }
  • 你還應該知道箭頭函數( => )能夠用來保留上下文。這個方法也能夠:

    asyncGreet () {
    this.someThingAsync()
    .then(() => {
    this.greet()
    })
    }

儘管我認爲最後一種方法並不優雅。

我很高興咱們解決了這個問題。

總結

祝賀你,你如今能夠放心地把你的程序放在互聯網上了。甚至運行起來可能都不會出岔子(可是一般會)Cheers \o/

若是還有什麼我應該提到的,請告訴我!

相關文章
相關標籤/搜索