【发布时间】:2018-10-02 10:29:17
【问题描述】:
这行代码有什么问题?
req.body.location && req.body.location.type = 'Point'
我只想添加一个类型属性,但我得到了错误
ReferenceError:分配中的左侧无效
但这会起作用
if(req.body.location) req.body.location.type = 'Point'
只是好奇,这两个语句的含义不一样,为什么第一个不起作用?
【问题讨论】:
-
试试
req.body.location && (req.body.location.type = 'Point')。 -
对
console中的我来说,它正在工作。 @CertainPerformance 你也可以翻转它req.body.location.type = 'Point' && req.body.location。没有? -
Node.js
req将永远存在。对于第二行。 Here is the fiddle.@CertainPerformance -
是的。虽然看起来节省代码。 It works by the way due to
precedence.()在 20 个中获得了最高的precedence。&&仅在 6 个中获得了precedence。@CertainPerformance -
因为
&&的precedence比=更高。所以它比较然后卡在=分配。()得到了最高的precedence并使正确的块被视为 1。所以它工作得最好。
标签: javascript