[英]What is the ClojureScript analogue of typeof … undefined from JavaScript?
[英]What is the ClojureScript analogue of setting an object value that didn't exist to null from JavaScript?
我正在使用該模式看到很多代碼:
if (typeof a.b === 'undefined') {
a.b = null;
現在,我將其翻譯為:
(if (not (exists (.-b a)))
(aset a b nil)
但我覺得我應該將此設置為:
(if (not (exists (.-b a)))
(aset a b (clj->js {}))
(因為在前一種情況下編譯器可能會完全消除該步驟)。
那合適嗎?還是我丟失了一些關鍵數據?
我的問題是: 將JavaScript中不存在的對象值設置為null的ClojureScript類似什么?
首先,如果嘗試模仿一些JavaScript,我建議使用:repl-verbose選項,因為它使在REPL上嘗試變體並立即查看生成的JavaScript非常容易。
如果您想完全模仿您的代碼,請set!
將達到目的:
(when (not (exists? (.-b js/a)))
(set! (.-b js/a) nil))
產生
((!(typeof a.b !== 'undefined'))?a.b = null:null)
但是,(也許這是一樣的超募編譯器行為的關注),以避免在封閉優化重命名(見本SO ), aget
和aset
可以用基於字符串的索引使用:
(when (not (exists? (aget js/a "b")))
(aset js/a "b" nil))
((!(typeof (a["b"]) !== 'undefined'))?(a["b"] = null):null)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.