我已经得到了这段代码,但无法获取 r.concat
部分,因为 concat
通常用于整个数组而不是其中的单个元素.
function doubleOddNumbers(numbers) {
return numbers.reduce((r, n) => n % 2 ? r.concat(n * 2) : r, [])
}
最佳答案
下面是注释的代码:
function doubleOddNumbers(numbers) {
return numbers.reduce( // reduce iterates over numbers and passes an accumulator from iteration to iteration
(r, n) => // the reducer function called for each element, r is the accumulator, n is the element
n % 2 // if the element is odd
? r.concat(n * 2) // then append its double to the accumulator
: r // otherwise return the accumulator unchanged
, []) // start with an empty array for the accumulator
}
关于javascript - 谁能解释一下这段代码:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56045833/