[英]How to set the variable to true or false based on the length using ternary operator in javascript?
I have an array named currentOrders
.我有一个名为currentOrders
的数组。
if its length is 1 then I want to set the variable output to true if not false using javascript.如果它的长度为 1,那么我想使用 javascript 将变量输出设置为 true 如果不是 false。
I writing something like this using ternary operator我用三元运算符写了这样的东西
const isOneOrder = currentOrders.length === 1 ? true : false;
I think the above can be rewritten still more good.我觉得上面的可以改写还是比较好。 but i am not sure how it can be rewritten.但我不确定如何重写它。
How can I rewrite this.我怎样才能重写这个。 could someone help me with this?有人可以帮我吗? thanks.谢谢。
Simply you can write like this.简单地你可以这样写。
const isOneOrder = currentOrders.length === 1;
===
operator will return true
if value and type are same and will return false
in othercases.如果值和类型相同, ===
运算符将返回true
否则将返回false
。
Therefore, no need to define true
or false
.因此,无需定义true
或false
。
you could write it like this你可以这样写
const isOneOrder = !!currentOrders.length;
when you add two !!
当你加两个时!!
it will convert the value to boolean它会将值转换为布尔值
You can completely remove the ternary operator:您可以完全删除三元运算符:
let currentOrders = [1]; const isOneOrder = currentOrders.length === 1; console.log(isOneOrder); currentOrders = [1, 2]; const isNotOneOrder = currentOrders.length === 1; console.log(isNotOneOrder);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.