简体   繁体   English

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

[英]Re-usable while loop function isn't looping

Still a little new to javascript so this might be an easy fix but could anyone tell me why the following code does not work? javascript还是有点新手,所以这可能是一个简单的解决方法,但是谁能告诉我以下代码为什么不起作用? I am trying to create a reusable function that will increment from count to countTo in increments of countBy. 我正在尝试创建一个可重用的函数,该函数将以countBy为增量从count递增到countTo。 I would like to vary those increments (either all evens, all odds, only numbers divisible by 5, etc). 我想更改这些增量(所有的偶数,所有的赔率,只有被5整除的数字,等等)。 Right now it is just printing out -10 and not looping. 现在,它只是打印出-10而不是循环播放。 Also it doesn't know count exists unless i make it global and I'm not sure why. 另外,除非我将其设置为全局且不确定原因,否则它不知道计数是否存在。 Thanks in advance! 提前致谢!

EDIT: initialized count with count = 0, it works now. 编辑:初始化计数,计数= 0,现在可以使用。 I'm still not sure why it doesn't just recognize the value of count when i pass it in as an argument though. 我仍然不确定为什么当我将其作为参数传递时,为什么它不仅仅识别count的值。 Are they not the same "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++;
});

Since this question is tagged with functional-programming I'll answer it using functional techniques. 由于此问题是用functional-programming标记的,因此我将使用功能技术来回答它。

Where you went wrong 你哪里出错了

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);
    }
}

Functional programming advises against things like this tho anyway – and in some languages, it's outright impossible to do. 无论如何,函数式编程都建议不要这样做-在某些语言中,这是绝对不可能做到的。 External state is discouraged and variable reassignment is usually an indicator for problems. 不鼓励外部状态,变量的重新分配通常是问题的指示器。 Let's start by adjusting how the code should work 让我们开始通过调整代码应该如何工作

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
});

Instead of relying upon external state, count , we will pass count into the function each loop. 而不是依赖外部状态count ,我们将在每个循环中将count传递给函数。 And rather than using count++ , although it would work in JavaScript since numbers are already immutable, it's better to get in the habit of using non-mutating functions. 而且,与其使用count++ ,尽管它已经可以在JavaScript中使用,因为数字已经是不可变的,但是最好养成使用非突变函数的习惯。 Also count + 1 makes it clear that a mutation is not necessary here and things like count + 2 would work if we wanted to count by twos – or count * 2 if we wanted to double the counter each time, etc. count + 1清楚地表明,突变是没有必要在这里以及诸如此类count + 2 ,如果我们想通过三三两两来算会工作-或count * 2 ,如果我们想在每次计数器增加一倍,等等。

To make this work, it's actually quite easy. 为了使这项工作,实际上很容易。 Below is a recursive function which continues looping until from is greater than to . 下面是一个递归函数,它将继续循环直到from大于到to为止。 Each loop will send the current counter value into the callback, f , which is expected to return the next value of the counter. 每个循环将当前计数器值发送到回调f ,该回调应返回计数器的下一个值。

 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 

There's nothing wrong with using a while -loop, but it's important to keep any mutable state localized to the looping function. 没有什么错用while -loop,但将继续定位于任何可变状态是很重要的looping功能。 The important lesson here is that the usage of our function looks exactly the same and even tho the implementation changed, there are still no side effects. 这里重要的一点是,我们的函数的用法看起来完全相同,即使更改了实现,仍然没有副作用。

 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 

当您递增count它没有任何值,因此它变为NaN

You are making a simple function complex by using inline function call which is not correct. 您通过使用不正确的内联函数调用使一个简单的函数变得复杂。 If question is about how to get this functionality, here is simple solution. 如果有关如何获得此功能的问题,这是简单的解决方案。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM