admin管理员组

文章数量:1405542

I have this variable :

var foobar = "Hi, my name is #{name}";

But if name is not defined at load of the page.. I'd like it to save "unknown" instead.

But writing something like this :

var foobar = "Hi, my name is #{typeof name === 'undefined' ? 'unknown' : name}";

Still returns the error, unknown variable name

I have this variable :

var foobar = "Hi, my name is #{name}";

But if name is not defined at load of the page.. I'd like it to save "unknown" instead.

But writing something like this :

var foobar = "Hi, my name is #{typeof name === 'undefined' ? 'unknown' : name}";

Still returns the error, unknown variable name

Share Improve this question edited Apr 12, 2013 at 16:28 gen_Eric 227k42 gold badges303 silver badges342 bronze badges asked Apr 12, 2013 at 15:53 TripTrip 27.1k48 gold badges162 silver badges281 bronze badges 6
  • 6 which is the templatting language used – Arun P Johny Commented Apr 12, 2013 at 15:56
  • What kind of syntax is "Hi, my name is #{name}"? – gen_Eric Commented Apr 12, 2013 at 16:02
  • 1 @RocketHazmat I think it's a Ruby thing. That's the only place I've seen that specific syntax. – Evan Davis Commented Apr 12, 2013 at 16:03
  • 1 @Trip, Please specify the template language being used. There will be no good answers to your question otherwise. – plalx Commented Apr 12, 2013 at 16:05
  • 1 @RocketHazmat indeed! All the more confusing for us, eh? :) – Evan Davis Commented Apr 12, 2013 at 16:08
 |  Show 1 more ment

4 Answers 4

Reset to default 3

Instead of making logic decisions within a string construct, do it outside for better performance and (far) more readable code:

name = name||'unknown';

I think a better method would be:

var name = name || "Unknown";
var foobar = 'Hi my name is ' + name;

Just put name in there. If it is undefined or null, it will be "false".

var foobar = "Hi, my name is " + name ? name : 'unknown';

With javascript ES6 syntax you can write this expression as follows,

const logName = (name) => `Hi, my name is ${name ? name : 'unknown'}`


console.log("foobar when name is undefined: ", logName());
console.log("foobar when name is abc: ", logName("abc"));

本文标签: jqueryCan you perform a ternary expression in a javascript string interpolationStack Overflow