最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to incorporate a boolean value in a string in JavaScript - Stack Overflow

programmeradmin5浏览0评论

Suppose I want to incorporate a boolean value in some string I print out, like

var x=1;
var y=2;
document.write("<p>The result is "+x==y+"</p>");

Normally, this does not give me the requred output. Is there a method to directly print boolean expressions in the document.write() itself? I do not want to use if-else and then assign separate values to variables and then print them. PS - I have just started learning JavaScript.

Suppose I want to incorporate a boolean value in some string I print out, like

var x=1;
var y=2;
document.write("<p>The result is "+x==y+"</p>");

Normally, this does not give me the requred output. Is there a method to directly print boolean expressions in the document.write() itself? I do not want to use if-else and then assign separate values to variables and then print them. PS - I have just started learning JavaScript.

Share Improve this question edited Dec 19, 2013 at 18:09 nsane asked Dec 19, 2013 at 17:55 nsanensane 1,7755 gold badges22 silver badges31 bronze badges 1
  • 2 Do you want to output true or false? – VisioN Commented Dec 19, 2013 at 17:56
Add a ment  | 

3 Answers 3

Reset to default 6

Put parentheses around the boolean expression:

document.write("<p>The result is " + (x == y) + "</p>");

If you don't, you're doing this:

document.write(("<p>The result is " + x) == (y + "</p>"));

And in general, don't use document.write.

This evaluates to a string:

(x==y).toString();

So you can use:

"<p>The result is " + (x==y).toString() + "</p>"
var x=1;
var y=2;
document.write("<p>The result is "+(x==y)+"</p>");

Will do

The result is false
发布评论

评论列表(0)

  1. 暂无评论