【问题标题】:Does Elm have a debugging function that can print an object to the console?Elm 是否有可以将对象打印到控制台的调试功能?
【发布时间】:2016-08-03 01:33:34
【问题描述】:

我希望能够检查运行时 javascript 对象。我可以将对象而不是字符串打印到控制台吗?

【问题讨论】:

  • log "my object is" object 怎么样?

标签: elm


【解决方案1】:

您可以使用Debug.log,例如:

import Html exposing (text)

f x = x * x

main =
  let
    dummy = Debug.log "dump tuple" (33, 55, f)
  in text "Hello, World!"

【讨论】:

    【解决方案2】:

    我在使用编码器时需要更丰富的日志记录,所以我最终为它写了一个port。这是working example on Ellie,这是代码:

    Main.elm

    port module Main exposing (main)
    
    import Browser
    import Html exposing (Html, button, div, text)
    import Html.Events exposing (onClick)
    import Json.Encode as E exposing (Value, int, object, string)
    
    
    type alias Model =
        { count : Int
        , name : String
        }
    
    
    initialModel : Model
    initialModel =
        { count = 0
        , name = "Foo"
        }
    
    
    encodeModel : Model -> Value
    encodeModel model =
        object
            [ ( "count", int model.count )
            , ( "name", string model.name )
            ]
    
    
    port jsonConsole : Value -> Cmd msg
    
    
    type Msg
        = ConsoleLogJson
    
    
    update : Msg -> Model -> ( Model, Cmd Msg )
    update msg model =
        case msg of
            ConsoleLogJson ->
                let
                    json =
                        encodeModel model
                in
                ( model, jsonConsole json )
    
    
    view : Model -> Html Msg
    view model =
        div [] [ button [ onClick ConsoleLogJson ] [ text "Log to console" ] ]
    
    
    subscriptions : Model -> Sub Msg
    subscriptions _ =
      Sub.batch []
    
    
    init : () -> ( Model, Cmd msg )
    init flags =
        ( initialModel, Cmd.none )
    
    
    main : Program () Model Msg
    main =
        Browser.element
            { init = init
            , subscriptions = subscriptions
            , view = view
            , update = update
            }
    

    index.html

    <html>
    <head>
      <style>
        /* you can style your program here */
      </style>
    </head>
    <body>
      <main></main>
      <script>
        var app = Elm.Main.init({ node: document.querySelector('main') })
        app.ports.jsonConsole.subscribe(function(json) {
          console.log(json)
        })
      </script>
    </body>
    </html>
    

    我确信可以进行改进,我很想听听他们的意见!

    【讨论】:

      【解决方案3】:

      很遗憾,没有。当您使用Debug.log 时,所有对象都会在发送到控制台之前转换为字符串。

      但是,您可以创建一个使用 Native 层输出实际对象的函数,但是,这是一个未记录的 API,建议仅将其用作最后的手段。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-12
        • 1970-01-01
        • 2018-04-08
        • 2017-12-15
        • 2019-11-23
        • 1970-01-01
        • 2023-01-14
        相关资源
        最近更新 更多