我应该同时使用 CoffeeScript 浸泡和存在运算符吗?
我正在编写一个接受 settings
对象的脚本,但在未提供设置的情况下使用默认值。
我刚刚写了以下这行 CoffeeScript:
iframe_width = settings?.iframe?.width? ? $iframe_body.width()
用简单的英语来说,我的意图是:
如果定义了
settings
对象,并且它定义了一个属性iframe
,并且iframe
属性定义了一个属性width< /code>,然后将后一个属性的值分配给变量
iframe_width
。否则,分配通过调用$iframe_body.width()
返回的值。
我的 CoffeeScript 代码是否反映了我的意图?它是表达该意图的最有效方式吗?对于所有的存在运算符 (?
) 来说,这似乎很尴尬,所以我想把它放在那里以获得一些反馈(编译后的 JavaScript 非常简洁和神秘,所以很难判断是否应该像故意的)。
另外,我不确定同时使用标准存在运算符 (?
) 及其访问器变体 (?.
) 是否存在冗余。
谢谢!
更新:
上面的代码似乎没有按预期工作;然而,这是
iframe_width = settings?.iframe?.width ? $iframe_body.width()
有道理的,因为我认为前面的代码实际上并没有访问 width
属性,而只是检查它的存在(甚至两次?)。在此代码中,我删除了 width
属性后面的 ?
,因为我认为这对于两个表达式之间的 ?
运算符是多余的。这看起来正确吗?
I'm working on a script that accepts a settings
object, but uses default values where settings are not provided.
I just wrote the following line of CoffeeScript:
iframe_width = settings?.iframe?.width? ? $iframe_body.width()
My intent, in plain English, is:
If the
settings
object is defined, and it defines a propertyiframe
, and theiframe
property defines a propertywidth
, then assign the value of the latter property to the variableiframe_width
. Otherwise, assign the value returned by calling$iframe_body.width()
.
Does my CoffeeScript code reflect my intent, and is it the most effective way to express that? It seems awkward with all of the existential operators (?
), so I wanted to put it out there for some feedback (the compiled JavaScript is very terse and cryptic, so it's hard to tell if should work as intended).
Also, I'm not sure whether there's any redundancy in using both the standard existential operator (?
) and its accessor variant (?.
) together.
Thanks!
Update:
The code above doesn't seem to work as expected; however, this does:
iframe_width = settings?.iframe?.width ? $iframe_body.width()
That makes sense, since I don't think the former code actually accesses the width
property, but rather just checks for its existence (twice, even?). In this code, I removed the ?
just after the width
property, since I think that's redundant with the ?
operator between the two expressions. Does that seem correct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
(注意:这个答案是在问题更新之前写的。正如提问者意识到的,
foo? ? bar
不仅仅是多余的 - 它实际上不起作用,因为foo?
计算结果为true
或false
,因此始终为非空。)您有两个很好的选择来简化此操作:一,您可以用
or
替换存在二元运算符:第二,你可以在
width
之后放弃?
——它是多余的:现在,你可以同时执行 当且仅当
iframe.width
永远不会是0
(因为0 或 x
是x
)。如果你能确定这一点,那就继续吧(Note: This answer was written before the question was updated. As the questioner realized,
foo? ? bar
isn't just redundant—it actually won't work, becausefoo?
evaluates totrue
orfalse
, and is therefore always non-null.)You have two good options for simplifying this: One, you could replace the existential binary operator with an
or
:Two, you could ditch the
?
afterwidth
—it's redundant:Now, you could do both if and only if
iframe.width
will never be0
(since0 or x
isx
). If you can be sure of that, go ahead and make it