在 JavaScript/jQuery 中等效的 Oracle NVL 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5167616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Oracle NVL function equivalent in JavaScript/jQuery
提问by tonyf
Is there an Oracle NVL function equivalent in JavaScript/jQuery. I would be interested to see an example of how it works.
在 JavaScript/jQuery 中是否有等效的 Oracle NVL 函数。我很想看看它是如何工作的一个例子。
采纳答案by Tim
Ternary operatortypically is used here.
此处通常使用三元运算符。
For example, if you're creating a dynamic action in Apex you can do something like this:
例如,如果您在 Apex 中创建动态操作,您可以执行以下操作:
( $v("P1_VAL1") ? $v("P1_VAL1") : $v("P1_VAL2") )
This will return the value of P1_VAL1if it's not blank, otherwise it will return the value of P1_VAL2.
这将返回的值P1_VAL1,如果它不为空,否则将返回的值P1_VAL2。
回答by unziberla
In Javascript this can actually be handled by the ||operator, that returns the first "valid" value.
在 Javascript 中,这实际上可以由||运算符处理,返回第一个“有效”值。
var a = null;
var b = "valid value";
var c = a || b; // c == "valid value"
Just keep in mind that "falsy"values are not only nullbut also for example empty string '', number 0and boolean value false. So you need to be sure that either you consider those with the same meaning as nullor your variables cannot assume those values, because in those cases you will also get the second value selected:
请记住,“假”值不仅null是空字符串'',数字0和布尔值也是空字符串false。因此,您需要确保要么考虑与这些具有相同含义null的变量,要么您的变量不能采用这些值,因为在这些情况下,您还将选择第二个值:
var a = "";
var b = "valid value";
var c = a || b; // c == "valid value"
回答by Bessem
function nvl(value1,value2)
{
if (value1 == null)
return value2;
return value1;
}
回答by Les Ey
Here's my solution for what it is worth
这是我对它的价值的解决方案
var ignoreNaN = false;
function nullButNot0(val) {
if (typeof val == 'number' && isNaN(val)) {
if (!ignoreNaN)
throw Error('NaN passed to nullButNot0()');
return true;
}
if (typeof val == 'object') {
try {
if (val.constructor === Array)
return false;
} catch (e) {
}
}
return (!val && val !== 0);
}
function nvl(s, defVal) {
// WARNING: not guaranteed to work with blank arrays
if (!nullButNot0(s))
return s;
if (!defVal)
defVal = '';
return defVal;
}

