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
- 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
4 Answers
Reset to default 3Instead 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
版权声明:本文标题:jquery - Can you perform a ternary expression in a javascript string interpolation? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744247308a2597081.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论