【问题标题】:Convert nested if/else to ternerary in React Native在 React Native 中将嵌套的 if/else 转换为三元
【发布时间】:2020-03-07 17:55:21
【问题描述】:
向我解释如何将现有的嵌套 if/else 转换为三元运算符。我查看了文档,但仍然无法实现我所需要的。
if(value){
if((value).match('google')) {
return 'Google'}
else if((value).match('apple')){
return 'Apple'}
else 'Other websites'
} else{
return 'Number'
}
这里的 {value} 是来自 JSON 的数据。 {value} 可以是链接或数字。
我想检查链接是否包含谷歌,所以给我看“谷歌”文本。如果它包含苹果,那么给我看苹果文字。如果其他人只显示“其他网站”文本。如果这不是链接,只需显示“数字”文本
【问题讨论】:
标签:
javascript
conditional-statements
conditional-operator
【解决方案1】:
首先检查值?
如果存在值,则检查值是否为 'google' ?如果是返回:
如果 value 不是 google 检查 value 是 'apple' ?如果是返回:
如果值不是苹果返回,否则:
如果没有值则返回'数字'
let value = 'apple'
let res = value? value.match('google')? 'Google':value.match('apple')?'Apple':'Otherwebsite':'Number';
console.log(res)
【解决方案2】:
const val = value ? (value).match('google') ? 'Google' : (value).match('apple') ? 'Apple' : 'Other websites' : 'Number';
【解决方案3】:
试试这个。
function func(value) {
return value ? value.match('google') ? 'Google' : value.match('apple') ? 'Apple' : 'Other websites' : 'Number';
}
console.log(func('google'));
console.log(func('apple'));
console.log(func('none'));
console.log(func());
【解决方案4】:
const val = isNaN(value) ? (value.match('google') ? "Google": ( value.match("apple")? "Apple": "Other Websites" )): "Number";