如何让var output
根据排名顺序显示var one OR two OR three Or four
(最高“一”最低“四”)并且不包括未定义。例如
var one = //undefined
var two = "yes121";
var three = "no";
var four = "yes";
var output = // should be "yes121" as `var two` has the higest rank that is not undefined.
输出为var输出= 1 + 2 + 3 + 4;但由于显而易见的原因,我所要求的是不必要的。
如果我有四个变量“一”“二”“三”和“四”我怎样才能将输出变量设置为排名最高的变量“一”(最低为“四”)排除排名较低的变量和排名较高的未定义变量。
答案 0 :(得分:0)
使用||
运算符。它将返回最左边的非虚假值,例如表达式
var output = one || two || three || four;
将返回"yes121"
。但非虚假意味着空字符串也将是假的;要检查undefined
,你真的必须遍历一系列值:
var vals = [undefined, "yes121", "no", "yes"];
var output = vals.reduce(function(a, b) {
return (typeof a == "undefined") ? b : a;
});
答案 1 :(得分:0)
我是否理解正确:您想要返回NAME最接近零的变量而忽略VALUE未定义的变量?
唯一的方法就是逐个测试它们,因为它们没有被定义:
var one = //undefined
var two = "yes121";
var three = "no";
var four = "yes";
var output;
if (one !=== undefined) output = one;
else if (two !=== undefined) output = two;
else if (three !=== undefined) output = three;
else if (four !=== undefined) output = four;
另外,你可以这样做:
var output = one || two || three || four;
但这可能会导致假表达问题。 (比如'',0,-1,NaN等)
然而:我认为你应该做什么创建一个数组,所以你可以循环它: