首页 > 解决方案 > 我如何让它记录每次迭代?

问题描述

function annoyingSong(start){
 for (let i = start; i >= 0; i--) {
  sol = `${i} bottles of soda on the wall, ${i} bottles of soda, take one down pass it around ${i-1} 
  bottles of soda on the wall` 
  return sol;
 }
}

console.log(annoyingSong(20))

这仅在第一次迭代时记录 sol 。如何让它返回或记录每次迭代?

标签: javascript

解决方案


这是实现。

function annoyingSong(start, fn) {
    for (let i = start; i >= 0; i--) {
        console.log(fn(i));
    }
}

function fn(count) {
    return `${count} bottles of soda on the wall, ${count} bottles of soda, take one down pass it around ${count - 1} bottles of soda on the wall`;
}

annoyingSong(20, fn);

推荐阅读