2 回答
TA贡献1850条经验 获得超11个赞
您可以将过滤器与连接一起使用。序列由数组中的序列定义。将any 替换为null,可以看到它会与/ 连接在一起。
下面的片段中的示例。
[swim, bike, run].filter(item => item !== null).join('/')
swim = null
bike = null
run = 'c'
console.log('Should return c =>', [swim, bike, run].filter(item => item !== null).join('/'))
swim = 'a'
bike = null
run = 'c'
console.log('Should return a/c =>', [swim, bike, run].filter(item => item !== null).join('/'))
swim = null
bike = '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('/'))
TA贡献1943条经验 获得超7个赞
尝试使用这个
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;
}
我所做的是根据可用性附加值并删除最终的值/
添加回答
举报