2016-05-29 140 views
-3
​​

我当前的代码如下,但当前缓冲区告诉我这是语法错误:意外的令牌如果。如何使用箭头函数返回一个数组,其所有偶数元素加1,奇数元素减1?

// 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;); 
+1

箭头函数的简明体形式具有以返回一个表达式; 'if'是一个语句,而不是一个表达式,所以你需要使用'{'和'return'。或者你可以使用三元运算符。 – 2016-05-29 19:32:57

+0

的[MDN文档】(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)示出的语法和示例。当你遇到问题时,请先阅读文档... –

回答

3

您可以使用此:

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

请注意,您在currentValue和你不应该使用if但三元运营商有一个拼写错误。

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

+0

谢谢,它的工作原理!它实际上是询问偶数和奇数currentValue,而不是索引。我更正了你的代码,如下所示:var my_function = some_array => some_array.map(currentValue => currentValue +(currentValue%2?-1:1)); – dsjkncdjksncdskjcn

+0

啊,我明白了。我在答案中做了同样的更正。 – trincot

相关问题