简体   繁体   English

Javascript:如果值不存在,则不输出该行

[英]Javascript: If the value doesn't exist, don't output the line

N00b here! N00b 在这里! I have addresses where each part needs to be on a separate line.我有地址,每个部分都需要在单独的行上。 But if there's nothing in the Address line_2 or Address line_3, then don't insert a line break.但是如果地址 line_2 或 Address line_3 中没有任何内容,则不要插入换行符。 How do I go about doing this?我该怎么做?

My javascript:我的javascript:

var html = "<b>" +first +"\xa0" +last +"</b> <br/>" + line_1 +"<br/>" 
+ line_2 +"<br/>"
+ line_3 +"<br/>" 
+ city +"\xa0" + state +"\xa0" +zipcode;

Thank you in advance!先感谢您!

You can use the ternary operator, it is a condensed if where您可以使用三元运算符,它是浓缩的 if where

var result = (if this is true) ? 'return this' : 'if not return this';

In your case, something like this在你的情况下,像这样

var html = "abc" + (line_2 == '' ? '' : line_2 + '<br>') + "xyz";

Use (line_2 ? line_2 +"<br/>" : "") which only adds the line_2 if defined and not null or else adds an empty string.使用(line_2 ? line_2 +"<br/>" : "")仅添加 line_2 如果定义且不为空,否则添加空字符串。

var html = "<b>" +first +"\xa0" +last +"</b> <br/>" + line_1 +"<br/>"
+ (line_2 ? line_2 +"<br/>" : "")
+ (line_3 ? line_3 +"<br/>" : "")
+ city +"\xa0" + state +"\xa0" +zipcode;

console.log(html);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM