Question

Comment écrivez-vous ce qui suit dans ClojurScript?

obj = {"a" : 4};
"a" in obj;

Était-ce utile?

La solution

Suite à la manière acceptée de vérifier si une propriété d'objet JS existe à l'aide de la méthode " HasownProperty " Nous pouvons le traduire comme suit:

(def foo (js-obj "bar" "baz"))
(.hasOwnProperty foo "bar")
;; => true
(.-bar foo)
;;=> "baz"
(.hasOwnProperty foo "car")
=> false
(.-car foo)
;;=> nil

Autres conseils

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top