Clojursept per verificare se una proprietà esiste in un oggetto JS
-
21-12-2019 - |
Domanda
Come scrivo il seguente in clojecript?
obj = {"a" : 4};
"a" in obj;
. Soluzione
Seguendo il modo accettato per verificare se esiste una proprietà dell'oggetto JS utilizzando il metodo " hawnproperty " possiamo tradurlo come segue:
(def foo (js-obj "bar" "baz"))
(.hasOwnProperty foo "bar")
;; => true
(.-bar foo)
;;=> "baz"
(.hasOwnProperty foo "car")
=> false
(.-car foo)
;;=> nil
. Altri suggerimenti
exists? was added to check for undefined
in ClojureScript :
(ns my.ns
(:require-macros [cljs.core :refer [exists?]]))
(if (exists? js/jQuery)
(println "jQuery"))
(println "no jQuery"))
One can also use aget
and nil?
to avoid calling JavaScript functions :
(def scope (js-obj))
(aset scope "var1" "Value")
(aget scope "var1") ;; "Value"
(aget scope "anotherVar") ;; nil
(nil? (aget scope "anotherVar")) ;; true
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow