【发布时间】:2020-07-04 05:32:52
【问题描述】:
必须有一种更清洁的方法来做到这一点我只是想不出一个原因这看起来很糟糕我想在 if 语句 atm 中检查多个状态这是我能想到的让它工作的唯一方法。我认为某种形式的数组可能会起作用,但我想不出如何做出反应?
calculate_bmi = () => {
if (this.state.Gender !== "") {
if (this.state.Goal !== "") {
if (this.state.Weight !== "") {
if (this.state.Height !== "") {
if (this.state.Age !== "") {
console.log(
this.state.Gender,
this.state.Goal,
this.state.Weight,
this.state.Height,
this.state.Age
);
} else {
alert(
"Please enter your Height, Weight and Age so we can achieve your goals!"
);
}
} else {
alert(
"Please enter your Height, Weight and Age so we can achieve your goals!"
);
}
} else {
alert(
"Please enter your Height, Weight and Age so we can achieve your goals!"
);
}
} else {
alert(
"Please enter your Height, Weight and Age so we can achieve your goals!"
);
}
} else {
alert(
"Please enter your Height, Weight and Age so we can achieve your goals!"
);
}
};
【问题讨论】:
-
你知道 JS 中的
&&和||运算符吗? -
我试过 && 它似乎没有用,但我不知道 '||'这是什么意思?
-
||表示“或”,如 if (this.state.Gender !== "" || this.state.Goal !== "") { // code }
-
有一个很棒的库叫做 lodash 可以帮助你。例如,以下答案显示了如何测试对象的值是否为空。将 _.pick 与以下答案链接是检查属性列表是否为空的一种巧妙方法。 stackoverflow.com/a/54447355/7034696
标签: javascript reactjs