Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
61 views
in Technique[技术] by (71.8m points)

javascript - If not empty or null in JS return function

I have Javascript function and I want to check multiple if statements in return.

If the value exist or is not null then it should return a row with information,

I am not sure how to do this, I am thinking something like this, E.g:

function format(d){
    return '<table cellpadding="5" cellspacing="0" border="0">' +
    if (name) {
     '<tr>' +
         '<td>Name:</td>' +
         '<td>' + d.name + '</td>' +
     '</tr>' } +
     if (place)
     '<tr>' +
         '<td>Place:</td>' +
         '<td>' + d.place + '</td>' +
     '</tr>' } +
     if (date) {
     '<tr>' +
         '<td>Date:</td>' +
         '<td>' + d.date + '</td>' +
     '</tr>' } +
    '</table>'; 
}
question from:https://stackoverflow.com/questions/66055911/if-not-empty-or-null-in-js-return-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Like Daniel pointed out, you could build the string on your way out like this:

function  myFormat(d) {
      let result = '<table cellpadding="5" cellspacing="0" border="0">';
      if (name){
        result += '<tr>' + '<td>Name:</td>' + '<td>' + d.name + '</td>' + '</tr>';
      }
      if (place){
        result += '<tr>' + '<td>Place:</td>' + '<td>' + d.place + '</td>' + '</tr>'; 
      }
      if (date){
        result += '<tr>' + '<td>Date:</td>' + '<td>' + d.date + '</td>' + '</tr>'; 
      }
      result += '</table>';
      return result;
}

Html elements could be combined together as well to make it simpler like this:

'<tr><td>Place:</td><td>' + d.name + '</td></tr>'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...