coffeescript学习


test2.coffee
stdin = process.openStdin()
stdin.setEncoding 'utf8'

stdin.on 'data', (input) ->
    name = input.trim()
    process.exit() if name == 'exit'
    console.log "Hello #{name}"
    console.log "Enter another name or 'exit' to exit"
console.log 'Enter your name'

C:\Users\cutepig>type test2.js
// Generated by CoffeeScript 1.9.1
(function() {
  var stdin;

  stdin = process.openStdin();

  stdin.setEncoding('utf8');

  stdin.on('data', function(input) {
    var name;
    name = input.trim();
    if (name === 'exit') {
      process.exit();
    }
    console.log("Hello " + name);
    return console.log("Enter another name or 'exit' to exit");
  });

  console.log('Enter your name');

}).call(this);

代码片段
coffee> nums = [1..10]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
coffee> isOdd = (n) -> n % 2 == 1
[Function]
coffee> odds = nums.filter isOdd
[ 1, 3, 5, 7, 9 ]
coffee> odds.reduce (a,b) -> a + b
25
    
清单 8. Web 页面中的 CoffeeScript

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
    <script
 src="http://jashkenas.github.com/coffee-script/extras/coffee-script.js">
 </script>
    <script type="text/coffeescript">
        gcd = (a,b) -> if (b==0) then a else gcd(b, a % b)
        $("#button").click ->
            a = $("#a").val()
            b = $("#b").val()
            $("#c").html gcd(a,b)
    </script>
</head>
<body>
    A: <input type="text" id="a"/><br/>
    B: <input type="text" id="b"/><br/>
    <input type="button" value="Calculate GCD" id="button"/> <br/>
    C: <span id="c"/>
</body>
</html>

posted on 2015-02-21 13:18  cutepig  阅读(170)  评论(0编辑  收藏  举报

导航