Exclamation mark behind assigned value: A = B ! C

*爱你&永不变心* 提交于 2020-01-25 20:05:38

问题


I am reading piece of company javaScript cods and I found the following:

seriesCode = pageRecord.getProperty('seriesCode')!'XXX' 

Does this mean that if first value is NULL the second on should be placed in seriesCode?


回答1:


Looks like FreeMarker template language, and yes, the ! operator, when appears on the right side of an operand gives a default value if the left side expression is null or a reference to a missing variable.




回答2:


well, your code is wrong and cannot be parsed. You might even get a weird not understandable error.

Does it mean that if first value is NULL the second on should be placed in seriesCode?

no, it's just wrong and cannot be understood by javascript. ! is a unary operator, so it's likely to fail in weird ways if you try to use it as a binary operator (in between two values).

What you're asking is done using the || operator:

seriesCode = pageRecord.getProperty('seriesCode')||'XXX';

you might see a trick with the ! unary operator, though being the double exclamation mark:

existsSeriesCode = !!pageRecord.getProperty('seriesCode');

the idea here is that with the first exclamation mark, you're converting your object into a boolean, where false means this variable is a reference to an instance, and true means the variable contains either null or undefined. Then the second exclamation mark is there to negate it again, meaning that true contains an instance, false contains either undefined or null.



来源:https://stackoverflow.com/questions/35852357/exclamation-mark-behind-assigned-value-a-b-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!