[英]javascript can i put a variable check inside a string
is something like this possible in javascript? 这样的事情可能在javascript中吗?
maybe I have a variable (in this case its a number) that sometimes might be undefined. 也许我有一个变量(在本例中为数字),有时可能是不确定的。 I'd like to sort of do some code right in the string to check the variable...
我想在字符串中执行一些代码来检查变量...
ps: I know that this throws throws an error! ps:我知道这会引发错误!
var mystring='<b class="my string">'+(if(variable){variable;}else{0;})+'</b>';
You can using the conditional operator ( ?:
) : 您可以使用条件运算符(
?:
:
var
variable = true,
mystring = 'Hello, ' + ( variable ? 'world' : 'nobody' ) + '!'
;
It seems the ternary operator ? 看来三元运算符? will be of some use for you :
将对您有用:
var like = true;
var myString = 'some string i ' + ( (like) ? 'really' : 'do not' ) + ' like' ;
The typeof
operator will specifically tell you if the variable is defined or not. typeof
运算符将特别告诉您变量是否已定义。
Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof 链接: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/typeof
eg 例如
var mystring = 'The variable ' + (typeof variable !== 'undefined' ? 'exists' : 'doesn\'t exist');
JSFiddle: http://jsfiddle.net/FlameTrap/AJfFk/1/ JSFiddle: http : //jsfiddle.net/FlameTrap/AJfFk/1/
var mystring = '<b class="my string">' + ( typeof variable !== undefined ) ? 'variable' : 0 + '</b>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.