如何使用箭头函数 return 一个数组,其所有偶数元素递增 1,奇数元素递减 1?

How to use an arrow function to return an array with all its even elements incremented by 1, and odd elements decremented by 1?

Task

You are given a variable, my_function. Your task is to assign it with an arrow function. The my_function should take an array as its parameter and return an array with all its even elements incremented by 1, and odd elements decremented by 1.

Note

  • DON'T use function instead of an arrow function.
  • DON'T print anything on the console.
  • Replace the blank (_________) with an arrow function.
  • The name of the array parameter can be anything. For example, some_array.

我当前的代码在下面,但是当前缓冲区告诉我有 SyntaxError: Unexpected token if.

// write the correct arrow function here
var my_function = some_array => some_array.map((currentValue, index) => if(index % 2 === 0) currentValue + 1; else currentValue - 1;);

你可以使用这个:

var my_function = some_array => some_array.map(
    (currentValue, index) => currentValue + (currentValue % 2 ? -1 : 1)
);

请注意,您在 currentValue 中有一个拼写错误,您不应使用 if,而应使用三元运算符。

此外,您可以通过交换条件和后面的子表达式来保存与零的比较 (== 0)。最后,我将 currentValue 移出了条件部分,因为它必须用于两种情况。