简体   繁体   English

javascript我可以在字符串中放入变量检查

[英]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' ) + '!'
;

JSFiddle demo . JSFiddle演示

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.

相关问题 如何将字符串放在javascript变量和“ echo”变量中 - How can I put a string inside a javascript variable and “echo” variables in it 如何将 url 放入 javascript 的字符串变量中? - How to put an url inside a string variable in javascript? 如何将 javascipt 代码原样放入 javascript 字符串变量中? - How can i put javascipt code as it is into javascript string variable? 如何检查文件是否包含 JavaScript 中的字符串或变量? - How can I check if a file contains a string or a variable in JavaScript? 如何使用JavaScript检查变量是否不为null或为空字符串? - How can I check if a variable is neither null or the empty string with javascript? 如何检查作为字符串引入的变量是 Javascript 中的数字还是字母? - how can I check if a variable brought as a string is a number or letter in Javascript? 如何检查javascript变量是否包含字符串? - How can I check if a javascript variable contains a string or not? 如何在JavaScript中检查一个字符串是否包含变量值? - How can I check if one string contains a variable value in JavaScript? 如何在JavaScript数组中放入JavaScript变量? - How do I put a javascript variable inside javascript array? 我们可以在javascript的构造函数中放入什么变量? - What variable can we put inside the construction function in javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM