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.

Share Improve this question edited Dec 31, 2024 at 18:54 j08691 208k32 gold badges267 silver badges280 bronze badges asked Feb 26, 2014 at 16:25 frequentfrequent 28.5k61 gold badges187 silver badges336 bronze badges 2
  • 2 Note that if x is an empty string, it will fallback to default_url in your current code. x needs to be falsy, not necessarily undefined and the empty string (along with null, undefined and 0) is falsy. – dee-see Commented Feb 26, 2014 at 16:29
  • Also a good point. Nice! – frequent Commented Feb 26, 2014 at 16:31
Add a comment  | 

2 Answers 2

Reset to default 38

You 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 (quotquot) to undefined in one line in JavaScriptStack Overflow