如何在clojurescript中编写以下内容?
obj = {"a" : 4};
"a" in obj;
答案 0 :(得分:8)
存在?是added来检查ClojureScript中的undefined
:
(ns my.ns
(:require-macros [cljs.core :refer [exists?]]))
(if (exists? js/jQuery)
(println "jQuery"))
(println "no jQuery"))
还可以使用aget
和nil?
来避免调用JavaScript函数:
(def scope (js-obj))
(aset scope "var1" "Value")
(aget scope "var1") ;; "Value"
(aget scope "anotherVar") ;; nil
(nil? (aget scope "anotherVar")) ;; true
答案 1 :(得分:6)
遵循接受的SO方式,使用方法“hasOwnProperty”检查是否存在js对象属性我们可以将其翻译如下:
(def foo (js-obj "bar" "baz"))
(.hasOwnProperty foo "bar")
;; => true
(.-bar foo)
;;=> "baz"
(.hasOwnProperty foo "car")
=> false
(.-car foo)
;;=> nil