简体   繁体   English

有什么方法可以简化这个if / else块吗?

[英]any way to simplify this if/else block?

 function (flag) {
 if (flag) {
 let id = "name",key = "age"
 return {id,key};
 } else {
 let id = "boy",key = "girl"
 return {id,key};
 }
 }

Any other readable solutions to handle this if/else? 还有其他可读解决方案可以解决此问题吗?

Consider just returning the plain object, rather than defining independent variables beforehand. 考虑只返回普通对象,而不是事先定义自变量。 You can also consider using the conditional operator and implicit return of an arrow function to cut down on the syntax noise, if you want: 您还可以考虑使用条件运算符和箭头函数的隐式返回,以减少语法干扰,如果需要:

const flagFn = flag => flag
  ? { id: 'name', key: 'age' }
  : { id: 'boy', key: 'girl' };

A couple options aside from what's already been answered: 除了已经回答的问题以外,还有几种选择:

const flagCheck = flag => {
    const id = flag ? 'name' : 'boy';
    const key = flag ? 'age' : 'girl';
    return { id, key };
};
const flagCheck = flag => ({
    id: flag ? 'name': 'boy',
    key: flag ? 'age': 'girl'
});

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

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