循环功能不循环时可重复使用

时间:2016-11-20 23:09:30

标签: javascript while-loop functional-programming

仍然有点新的JavaScript,所以这可能是一个简单的修复,但任何人都可以告诉我为什么以下代码不起作用? 我正在尝试创建一个可重用的函数,它将以countBy为增量从count增加到countTo。我想改变这些增量(所有均匀,所有赔率,只能被5整除的数字等)。现在它只是打印-10而不是循环。此外,它不知道计数存在,除非我使它全球化,我不知道为什么。 提前谢谢!

编辑:初始化计数,计数= 0,现在可以正常工作。我仍然不确定为什么它不仅仅是在我将其作为参数传递时才识别count的值。它们不一样“数”吗?

//count = incrementing variable
//countTo = final result
//countBy = how we should increment count
var count;
function looping(count, countTo, countBy) {
    while(count <= countTo) {
        console.log(count);
        count = countBy(count);
    }
}
console.log("-10 to 19");
var counting1 = looping(-10, 19, function () {
    return count++;
});

3 个答案:

答案 0 :(得分:0)

由于此问题标有functional-programming,我将使用功能技巧回答。

你出错的地方

var count;
function looping(count, countTo, countBy) {
    // because you named a parameter `count`, you shadowed the external `count` variable
    while(count <= countTo) {
        console.log(count);
        // this doesn't reassign outer count
        // instead it reassigns local count and is discarded after function exits
        count = countBy(count);
    }
}

功能性编程建议反对这样的事情 - 在某些语言中,它是完全不可能做到的。不鼓励外部状态,可变重新分配通常是问题的指标。我们首先调整代码 的工作方式

var count; // no need for external state
var counting1 = looping(-10, 19, function (count) { // use local parameter
    return count++; // ++ is a mutating function
    return count + 1
});

我们不会依赖外部状态count,而是将count传递给每个循环的函数。而不是使用count++,虽然它可以在JavaScript中工作,因为数字已经是不可变的,但是养成使用非变异函数的习惯会更好。此外count + 1明确表示此处不需要变异,如果我们想要计算两次,则count + 2之类的东西会起作用 - 或count * 2如果我们想每次都将计数器加倍,等

要做到这一点,实际上很容易。下面是一个递归函数,它继续循环,直到from大于to。每个循环都会将当前计数器值发送到回调函数f,该回调函数将返回计数器的下一个值。

&#13;
&#13;
function looping (from, to, f) {
  if (from > to)
    return from
  else
    return looping (f (from), to, f)
}

looping (-3, 3, function (count) {
  console.log (count)
  return count + 1 // count by 1
})
// -3, -2, -1, 0, 1, 2, 3
// => 3

looping (-3, 3, function (count) {
  console.log (count)
  return count + 2 // count by 2
})
// -3, -1, 1, 3
// => 3
&#13;
&#13;
&#13;

使用while - 循环并没有错,但将{em>本地化的任何可变状态保存到looping函数非常重要。这里重要的一点是,我们函数的用法看起来完全一样,即使实现发生了变化,仍然没有副作用。

&#13;
&#13;
function looping (from, to, f) {
  while (from < to) from = f (from)
  return from
}

looping (-3, 3, function (count) {
  console.log (count)
  return count + 1 // count by 1
})
// -3, -2, -1, 0, 1, 2, 3
// => 3

looping (-3, 3, function (count) {
  console.log (count)
  return count + 2 // count by 2
})
// -3, -1, 1, 3
// => 3
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

count在您递增时没有值,因此它变为NaN

答案 2 :(得分:-1)

通过使用不正确的内联函数调用,您正在构建一个简单的函数复合体。如果问题是如何获得此功能,这是一个简单的解决方案。

function looping(count, countTo, countBy) {
    while(count <= countTo) {
        console.log(count);
        count += countBy;
    }
}
console.log("-10 to 19");
var step = 2;
var counting1 = looping(-10, 19, step);
相关问题