[英]What is the behaviour called where javascript outputs a non-boolean value if entire expression is true
I know this question has been asked for before, but I can't seem to find the right keywords to find my answer.我知道以前有人问过这个问题,但我似乎找不到合适的关键字来找到我的答案。
In javascript, you can do this在 javascript 中,你可以这样做
console.log(true && "hello world"); // prints hello world
console.log(false && "hello world"); // prints false
What is this behaviour called?这种行为叫什么? Where javascript will output the contents of a variable if the entire expression evaluates to true?
如果整个表达式的计算结果为真,javascript 将 output 变量的内容在哪里?
In the React world, This is called Conditional Rendering using the &&
operator.在 React 世界中,这称为使用
&&
运算符的条件渲染。 This technique leverages how Javascript short-circuits comparisons to change the view;该技术利用 Javascript 如何短路比较来改变视图; in this case, a logged value.
在这种情况下,记录值。 It is a concise and useful way to dynamically render different objects as properties change.
这是一种在属性更改时动态渲染不同对象的简洁而有用的方法。
If you weren't rendering, it would just be a good old-fashioned short-circuit, which has been used for decades, and goes all the way back to Kernaghan and Ritchie and C language.如果你不渲染,它只是一个很好的老式短路,已经使用了几十年,并且一直追溯到 Kernaghan 和 Ritchie 以及 C 语言。 Eg the OR operator can be used when referencing object properties to guard against
undefined
values;例如,当引用 object 属性以防止
undefined
的值时,可以使用 OR 运算符; eg:例如:
const cheese = {}
console.log(cheese.cheddar) // unsafe
console.log(cheese.cheddar || "") // safe
Here, we don't really care about the actual value, we just need a truthy
or falsy
resolution.在这里,我们并不真正关心实际值,我们只需要一个
truthy
或falsy
的分辨率。
Also note the double-bang !!
还要注意双响
!!
operator, which will convert the whole darn expression to a boolean:运算符,它将整个该死的表达式转换为 boolean:
console.log(!!(true && "hello world")) // true
References: https://reactjs.org/docs/conditional-rendering.html https://codeburst.io/javascript-short-circuit-conditionals-bbc13ac3e9eb What is the?!参考文献: https://reactjs.org/docs/conditional-rendering.html https://codeburst.io/javascript-short-9-b Whatisconditionals-bbst.io/javascript-short-9-eb- (not not) operator in JavaScript?
JavaScript 中的(不是不是)运算符?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.