【问题标题】:Coffeescript not converting properlyCoffeescript 没有正确转换
【发布时间】:2012-05-06 16:43:47
【问题描述】:

我正在用 ruby​​ on rails 制作一个应用程序,这是我的咖啡脚本文件之一
我相信我的代码已正确缩进,但仍然出现错误。
我在下面的评论中标记了给我错误的行。
请帮忙!

jQuery ->


    today_date = new Date()
    month = today_date.getMonth()
    day = today_date.getDay()


    pkpstyle= [
        featureType: "landscape.natural"
        elementType: "geometry"
        stylers: [
            lightness: -29
        ,
            hue: "#ffee00"
        ,
            saturation: 54
         ]
    ,
        featureType: "poi.park"
        stylers: [
            lightness: -35
        ,
            hue: "#005eff"
         ]
    ,
        featureType: "road.arterial"
    ,
        featureType: "road.arterial"
        stylers: [ lightness: 45 ]
     ]


    tempDay = 4
    //I get an error here saying Uncaught TypeError: undefined is not a function
    today_latlng = getLatlng(stops[tempDay])

    markericon = new google.maps.MarkerImage("/assets/cycling.png")
    myOptions =
        center: today_latlng
        zoom: 12
        minZoom: 4
        styles: pkpstyle
        mapTypeId: google.maps.MapTypeId.ROADMAP

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions)
    for i of stops
        latlng = getLatlng(stops[i].latlng)
        marker = new google.maps.Marker(
            map: map
            icon: markericon
            position: latlng
        )

    getLatlng = (loc) ->
        loc_split = loc.split(", ")
        lat = loc_split[0]
        lng = loc_split[1]
        new google.maps.LatLng(lat, lng)

【问题讨论】:

  • getLatLong 在此处计算为未定义。有什么问题? (Coffeescript 允许这样的前向声明吗?JavaScript 中的 FunctionStatements but not "var f = func" 语句允许前向声明。JS 的最终结果是什么?我想像 var.. . 因此undefined.)
  • 您是否将此代码从 Javascript 转换为 CoffeeScript?

标签: javascript google-maps-api-3 coffeescript


【解决方案1】:

这个 CoffeeScript:

today_latlng = getLatlng(stops[tempDay])
getLatlng = (loc) ->
    loc_split = loc.split(", ")
    lat = loc_split[0]
    lng = loc_split[1]
    new google.maps.LatLng(lat, lng)

或多或少与此 JavaScript 相同:

var today_latlng, getLatLng;
today_latlng = getLatLng(stops[tempDay])
getLatLng = function(loc) { ... };

所以当你getLatLng(stops[tempDay]) 时你确实有一个getLatLng 变量,但是直到之后你尝试将它作为一个函数调用时你才给它赋值。您需要将getLatLng定义为一个函数,然后再将其视为一个函数:

getLatlng = (loc) ->
    loc_split = loc.split(", ")
    lat = loc_split[0]
    lng = loc_split[1]
    new google.maps.LatLng(lat, lng)
#...
today_latlng = getLatlng(stops[tempDay])

另外,如果stops 是一个数组,那么你不应该使用of 循环,你应该使用in loop

for p in stops
    latlng = getLatlng(p.latlng)
    #...

of 循环与 for ... in JavaScript 循环相同,它可以对数组做一些有趣的事情,in 循环在 JavaScript 中最终成为 for(;;) 循环,并且在数组中表现良好.我不知道stops 是什么,所以这可能不适用,我只是根据它的使用方式和i 索引变量来猜测。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 2016-05-20
    • 2018-06-07
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多