我想能够检查一个运行时的JavaScript对象。我可以将一个对象打印到控制台而不是字符串吗?
例如,您可以使用Debug.log
:
import Html exposing (text)
f x = x * x
main =
let
dummy = Debug.log "dump tuple" (33, 55, f)
in text "Hello, World!"
很遗憾,不行。当使用Debug.log
时,在发送到控制台之前,所有对象都会被转换为字符串。
但是,您可以创建一个函数,使用本地层输出实际的对象。然而,这是一个未记录的API,建议只在必要时使用。
在编写编码器时,我需要更丰富的日志记录,因此我最终为其编写了一个端口
。这是一个在Ellie上的工作示例,以下是代码:
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
}
<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>
我相信还有很多可以改进的地方,我很愿意听取建议!
let
_= Debug.log "string1" "string2"
in
你可以用变量替换任意一个"字符串",而不是使用字符串,只需删除引号。可以替换两个或仅一个。 你还可以用元组("string1", "s")替换任意一个"字符串",看起来像这样。
let
_= Debug.log ("string1", "string2") "string3"
in
adr : Float -> Float -> Float
adr revenue rooms =
let
_= Debug.log rooms revenue
in
if rooms /= 0 then
revenue / rooms
else
0
adr : Float -> Float -> Float
adr revenue rooms =
let
_= Debug.log "Rooms" rooms
in
if rooms /= 0 then
revenue / rooms
else
0
这将安慰房间,12
log "my object is" object
怎么样? - Lucio