2012-01-20 20 views
0

功能我剛開始學的CoffeeScript,它的偉大,但它的棘手..字符串不是Coffescript

我試着翻譯代碼,在Javascript中努力的CoffeeScript

,我失敗了很多,在鏈接我張貼3種膏

  1. js.js是原代碼,工作
  2. cs.coffee是相同的版本,但在CoffeeScript中
  3. compiled.js通過JS

的CS編譯器版本在翻譯JS翻譯我得到的錯誤「字符串不是一個函數」的地方在返回映射拉姆達

gist source code link

+0

您使用兩個for循環時,你可以使用一個:( – Raynos

回答

3
  1. CoffeeScript中的@this.

所以,你原來的js有:

if (input1.val().length <= 4 ... 

你的CoffeeScript應該有

if input1.val() <= 4 
  1. 如果你在你原來的JS $(this),你仍然需要$(this)在你的CoffeeScript。所以

    或@ input1.map( - > this.val()匹配(/ \ S + /克))長度不爲0

應該是:

or @input1.map(-> $(this).val().match(/\s+/g)).length not 0 

我不能直接看到任何其他問題 - 嘗試一下,看看它是否有效,或者是否還有錯誤。

[編輯]

還有其他問題,如提及到not 0並且還包圍很大程度上關係。這裏有一個工作(我認爲)的CoffeeScript:

if input1.val() <= 4 \ 
    or (input1.map(-> $(this).val().match(/\s+/g)).length != 0) \ 
    or (input1.map(-> $(this).val().match(/[^A-Za-z0-9]/g)).length != 0) 
    then input1.attr('id','error-highlight'); 
    else input1.attr('id','success-highlight'); 

它變成:

(function() { 
    if (input1.val() <= 4 || (input1.map(function() { 
     return $(this).val().match(/\s+/g); 
    }).length !== 0) || (input1.map(function() { 
     return $(this).val().match(/[^A-Za-z0-9]/g); 
    }).length !== 0)) { 
     input1.attr('id', 'error-highlight'); 
    } else { 
     input1.attr('id', 'success-highlight'); 
    } 
    }).call(this); 

它看起來是正確的。

+0

如果我脫光了@輸入1 - 它說,輸入1沒有定義,並根據官方網站/文檔指南你應該使用@與變量!=正在幫助,但這很奇怪,coffescript.org說,「不是」是相同的!=和!= is!==;),我想我真的不需要額外的(@ input1 ...)無論如何,我的代碼由於$(this)和!=我現在已經工作了一半了 - 我想我可以修復它進一步 – Umren

+0

考慮使用'.any(...)'而不是'.map(...)。length isnt 0' – grncdr

+0

@grncdr該方法被稱爲'some()'而不是'any()'。 –

9

.length not 0

被編譯成

.length(!0)

+0

是的,這是非常奇怪的行爲 – Umren

+17

@Umren我認爲你正在尋找'.length isnt 0'。 CoffeeScript將'isnt'編譯成'!=='。 –

+1

@CoffeeScriptFanboy爲什麼你不喜歡 – Raynos