admin管理员组文章数量:1178528
I have a method (URItemplate) which I need to return undefined in case variables are not defined. Currently I'm doing this:
var x = UriTemplate.parse(value || "").expand({"some":"properties"} || {});
In case value
and my expand object {}
are passed as empty string and empty object, x equates to ""
.
I'm wondering if there is anything I can do with an empty string to convert it to undefined, so I can later call...
$.ajax({"url": x || default_url})...
Of course there is if-else
or ?:
and my ||
is also an if-else, but I'm wondering if there is another way to do this as a one-liner.
I have a method (URItemplate) which I need to return undefined in case variables are not defined. Currently I'm doing this:
var x = UriTemplate.parse(value || "").expand({"some":"properties"} || {});
In case value
and my expand object {}
are passed as empty string and empty object, x equates to ""
.
I'm wondering if there is anything I can do with an empty string to convert it to undefined, so I can later call...
$.ajax({"url": x || default_url})...
Of course there is if-else
or ?:
and my ||
is also an if-else, but I'm wondering if there is another way to do this as a one-liner.
2 Answers
Reset to default 38You can use ||
:
x = x || undefined;
If "x" has any falsy value (including the empty string), it will end up as undefined
.
edit—Now it's 2024, and the above is fine, but there's a better way to make the above sort of "fix" to values when you do care about things like 0 and the empty string:
x ??= undefined;
The ??
operator, and the assignment operator ??=
, work like ||
but it only tests for null
and undefined
. Thus you don't have the annoying problem with other "falsy" values. The statement above will make sure that the value of x
is undefined
if it's currently either null
or undefined
.
So good old ||
still works when you want to "normalize" any falsy value, and ??
is great for when you're just worried about null
and undefined
.
You could also use a function :
// "def" means "default (to undefined)"
function def(v) { if (v) return v; }
x = def(x);
y = def(y);
Well, you need at least two lines (cheating a bit) =D
版权声明:本文标题:Is it possible to convert an empty string ("") to undefined in one line in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738100162a2063562.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
x
is an empty string, it will fallback todefault_url
in your current code.x
needs to be falsy, not necessarilyundefined
and the empty string (along withnull
,undefined
and0
) is falsy. – dee-see Commented Feb 26, 2014 at 16:29