[英]How to use an arrow function to return an array with all its even elements incremented by 1, and odd elements decremented by 1?
任務
您將獲得一個變量 my_function。 你的任務是給它分配一個箭頭函數。 my_function 應該接受一個數組作為其參數,並返回一個數組,其中所有偶數元素遞增 1,奇數元素遞減 1。
筆記
- 不要使用函數而不是箭頭函數。
- 不要在控制台上打印任何東西。
- 用箭頭函數替換空白 (_________)。
- 數組參數的名稱可以是任何名稱。 例如,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
移出了條件部分,因為這兩種情況都必須使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.