如何简化基于多种条件的函数打印

我有一个函数,它根据 3 个输入变量格式化字符串。我已经使用 if / else if 语句完成了它,但我相信应该有一种更简单的方法来做到这一点。我有 3 个变量,它们都可以是字符串或 null。我正在使用 javascript / 角度。我可以想象有一个类似的情况,有 5 个变量,这会增加显着的 if 数量,如何简化它?


formatDistance(){

let distance;

let swim;

let bike;

let run;

swim = this.sport.swim ? this.sport.swim : null;

bike = this.sport.bike ? this.sport.bike : null;

run = this.sport.run ? this.sport.run : null;


if(swim && bike && run) {

  distance = swim + ' / ' + bike + ' / ' + run; 

}

else if(swim && bike && !run) {

  distance = swim + ' / ' + bike; 

}

else if(swim && !bike && run) {

  distance = swim + ' / ' + run; 

}

else if(!swim && bike && run) {

  distance = bike + ' / ' + run; 

}

else if(!swim && !bike && run) {

  distance = run; 

}

else if(!swim && bike && !run) {

  distance = bike; 

}

else if(swim && !bike && !run) {

  distance = swim; 

}

else {

  distance = '';

}


 return distance;

}


一只甜甜圈
浏览 149回答 2
2回答

慕盖茨4494581

您可以将过滤器与连接一起使用。序列由数组中的序列定义。将any 替换为null,可以看到它会与/ 连接在一起。下面的片段中的示例。[swim, bike, run].filter(item => item !== null).join('/')swim = nullbike = nullrun = 'c'console.log('Should return c =>', [swim, bike, run].filter(item => item !== null).join('/'))swim = 'a'bike = nullrun = 'c'console.log('Should return a/c =>', [swim, bike, run].filter(item => item !== null).join('/'))swim = nullbike = 'b'run = 'c'console.log('Should return b/c =>', [swim, bike, run].filter(item => item !== null).join('/'))swim = 'a'bike = 'b'run = 'c'console.log('Should return a/b/c =>', [swim, bike, run].filter(item => item !== null).join('/'))

杨__羊羊

尝试使用这个formatDistance(){    let distance = "";    let swim;    let bike;    let run;    swim = this.sport.swim ? this.sport.swim : null;    bike = this.sport.bike ? this.sport.bike : null;    run = this.sport.run ? this.sport.run : null;        if(swim != null)      distance = distance + swim + ' / ';    if(bike != null)      distance = distance + bike + ' / ';    if(run != null)      distance = distance + run + ' / ';    distance = distance.substring(0, distance.length - 1);    return distance;}我所做的是根据可用性附加值并删除最终的值/
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript