如何将该if语句转换为箭头函数?

时间:2018-09-01 10:51:01

标签: javascript if-statement arrow-functions

我有一个带有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_a限制的。我真的是箭头功能的新手,希望能对此有所帮助。

3 个答案:

答案 0 :(得分:2)

    4 =     2^2
    8 =     2^3
    9 =     3^2
   16 =     2^4
   25 =     5^2
   27 =     3^3
   32 =     2^5
   36 =     6^2
   49 =     7^2
   64 =     2^6
   81 =     3^4
  100 =    10^2
  121 =    11^2
  125 =     5^3
  128 =     2^7
  144 =    12^2
  169 =    13^2
  196 =    14^2
  216 =     6^3
  225 =    15^2
  243 =     3^5
  256 =     2^8
  289 =    17^2
  324 =    18^2
  343 =     7^3
  361 =    19^2
  400 =    20^2
  441 =    21^2
  484 =    22^2
  512 =     2^9
  529 =    23^2
  576 =    24^2
  625 =     5^4
  676 =    26^2
  729 =     3^6
  784 =    28^2
  841 =    29^2
  900 =    30^2
  961 =    31^2
 1000 =    10^3
 1024 =    2^10

答案 1 :(得分:1)

您可以使用逗号运算符来链接条件,而且由于您没有else分支,因此使用三进制也没有意义。这是与您的功能相同的代码:

 const deflect = () => (
   number_a >= 600 && (ball_velocity_a = -ball_velocity_a),
   number_b >= 600 && (ball_velocity_b = -ball_velocity_b),
   undefined
 );

但是IMO实际上比您的原始功能差很多。

答案 2 :(得分:0)

我会尽量避免在辅助函数内使用全局变量,硬编码常量以及误导函数名(如果未实际发生反射/偏转,则调用反射/偏转)。

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);