这是for循环方法,我想要的结果也与下面的代码相同
function reduce (dollars) {
let arr = [];
let change = [10000,5000,2000,1000,500,200,100,50,20,10,1];
if(dollars === 0) return arr
for(key of change){
if(key <= dollars) return arr.concat(key).concat(reduce (dollars -= key));
}
}
console.log(reduce(900))
console.log(reduce(9000))
如何使用reduce和以递归方式使用spread语法,
我递归使用reduce
时遇到一些错误,并且concat函数被称为not function
这是代码,
function reduce(dollar) {
let change = [10000,5000,2000,1000,500,200,100,50,20,10,1];
if(dollar === 0) return c
let c = change.reduce((ar, el) => {
if(dollar >= el) {
return ar.concat(el).concat(reduce(dollar-=el))
}
}, [])
}
let [ one, two, three] = [10020,9000,900];
console.log(reduce(one));
console.log(reduce(two));
console.log(reduce(three));
reduce(one)的输出为[ 10000, 20 ]
答案 0 :(得分:2)
请确保reduce处理程序始终返回数组,因为该处理程序期望ar
是一个数组。如果在化简处理程序中返回undefined
,它将作为ar
传递到下一个化简迭代,这就是您得到错误的原因。
另外,请确保在返回之前定义了c
,或如下所示修改代码,以避免完全需要c
:
function reduce(dollar) {
let change = [10000,5000,2000,1000,500,200,100,50,20,10,1];
/* if dollar === 0 then return [] */
if (dollar === 0) return [];
/* Return reduced result (ie "c" in original code) */
return change.reduce((ar, el) => {
/*
While el deducted from dollar yields positive value,
*/
while (dollar - el >= 0) {
/*
then decrement dollar amout by current el and,
*/
dollar -= el;
/*
add el to current result
*/
ar = ar.concat(el)
}
/*
Return resulting ar array
*/
return ar;
}, [])
}
let [ one, two, three ] = [ 10020, 9000, 900 ];
console.log(reduce(one));
console.log(reduce(two));
console.log(reduce(three));