[英]How can I convert this if statement to an arrow function?
我有一個if語句的函數說:
function reflect() {
if (number_a >= 600) {
ball_velocity_a = -ball_velocity_a }
if (number_b >= 600) {
ball_velocity_b = -ball_velocity_b
}}
我正在嘗試將此功能轉換為箭頭功能
const deflect = () => number_a >= 600 ? ball_velocity_a = -ball_velocity_a :
但是我不確定在以下之后放什么:
因為ball_velocity_b
是用number_b
而不是number_b
來number_a
。 我是箭頭功能的新手,並希望得到一些幫助。
var deflect = () => {
ball_velocity_a = number_a >= 600 ? -ball_velocity_a : ball_velocity_a;
ball_velocity_b = number_b >= 600 ? -ball_velocity_b : ball_velocity_b;
};
您可以使用逗號運算符來鏈接條件,因為您沒有else
分支,使用三元組是沒有意義的。 這是與您的函數相同的代碼:
const deflect = () => (
number_a >= 600 && (ball_velocity_a = -ball_velocity_a),
number_b >= 600 && (ball_velocity_b = -ball_velocity_b),
undefined
);
但IMO實際上比你原來的功能更糟糕。
我會盡量避免使用全局變量,輔助函數內部的硬編碼常量和誤導性函數名稱(如果實際上沒有反射/偏轉,則調用reflect / deflect)。
const adjustVelocityComponent = (velocity, position, maxPosition) => {
if (position >= maxPosition) // probably also check if position <= 0
return -velocity;
return velocity;
};
ball_velocity_a = adjustVelocityComponent(ball_velocity_a, number_a, 600);
ball_velocity_b = adjustVelocityComponent(ball_velocity_b, number_b, 600);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.