简体   繁体   English

将JavaScript中不存在的对象值设置为null的ClojureScript类似什么?

[英]What is the ClojureScript analogue of setting an object value that didn't exist to null from JavaScript?

I'm seeing lots of code using the pattern: 我正在使用该模式看到很多代码:

if (typeof a.b === 'undefined') {
  a.b = null;

Now I'm translating this to: 现在,我将其翻译为:

(if (not (exists (.-b a)))
  (aset a b nil)

But I feel like I should be setting this to: 但我觉得我应该将此设置为:

(if (not (exists (.-b a)))
  (aset a b (clj->js {}))

(Because the compiler may eliminate the step entirely in the former case). (因为在前一种情况下编译器可能会完全消除该步骤)。

Is that appropriate - or am I losing some crucial data? 那合适吗?还是我丢失了一些关键数据?

My question is: What is the ClojureScript analogue of setting an object value that didn't exist to null from JavaScript? 我的问题是: 将JavaScript中不存在的对象值设置为null的ClojureScript类似什么?

First, if attempting to imitate some JavaScript, I'd recommend the :repl-verbose option, as it makes it very easy to try variants at the REPL and immediately see the resulting JavaScript. 首先,如果尝试模仿一些JavaScript,我建议使用:repl-verbose选项,因为它使在REPL上尝试变体并立即查看生成的JavaScript非常容易。

If you want to exactly imitate your code, then set! 如果您想完全模仿您的代码,请set! will do the trick: 将达到目的:

(when (not (exists? (.-b js/a)))
  (set! (.-b js/a) nil))

produces 产生

((!(typeof a.b !== 'undefined'))?a.b = null:null)

But (and perhaps this is the same as the concern raised over compiler behavior), to avoid renaming during Closure optimizations (see this SO ), aget and aset can be used with a string-based index: 但是,(也许这是一样的超募编译器行为的关注),以避免在封闭优化重命名(见本SO ), agetaset可以用基于字符串的索引使用:

(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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM