循环功能

时间:2012-07-12 01:05:13

标签: javascript function loops while-loop

我正在尝试让这个功能在javascript中正常工作,它正常工作我可以发生的事情是底部 console.log(工作(“加仑水从地毯中提取出来。”)); 我无法得到“从地毯中提取出的加仑水”。显示在同一行代码中。

// Global variable
var waterGallons = 40

var work = function(total) {
    var water = 0;
    while (water < waterGallons) {
        console.log("The carpet company was called out to extract " + water + " gallons of water.")
        water+=4;
    };
    return waterGallons;
}

console.log (work(" gallons of water has been extracted from the carpet."));

所以使用我得到帮助的答案是我出来的,因为我需要使用全局变量。所以我的故事会因改变全局变量而改变。

var total = 40

var work = function(total) {
    var water = 0;
    while (water < total) {
        console.log("The carpet company was called out to extract " + water + " gallons of water.")
        water+=4;
    };
    return water;
}

console.log (work(total) + " gallons of water has been extracted from the carpet.");

我想再次感谢你们。我仍然有一个布尔函数,一个使用for循环函数的数组,还有一个程序。所以使用这个我应该能够理解如何创建我的作业的下一部分。

2 个答案:

答案 0 :(得分:1)

函数work的参数对应于形式参数total,它永远不会打印或以其他方式使用。如果你想将它打印到控制台,那么,你必须将它打印到控制台。

目前尚不清楚你要做什么,但这是一种可能性:

var waterGallons = 40;
var work = function() {
    var water = 0;
    while (water < waterGallons) {
        console.log("The carpet company was called out to extract " + 
                     water + " gallons of water.")
        water += 4;
    };
    return water;
}

console.log(work() + " gallons of water has been extracted from the carpet.");

如果确实希望将字符串作为参数传递给work并将其写入内部该函数,则使用{{1 }}。请记住保留我在示例中删除的console.log(total)参数。

答案 1 :(得分:0)

另一个版本(猜测)基于lwburk之前的回答:

var work = function(total) {
    var water = 0;
    while (water < total) {
        console.log("The carpet company was called out to extract " + 
                     water + " gallons of water.")
        water += 4;
    };
    return water;
}

console.log (work(40) + " gallons of water has been extracted from the carpet.");

这将允许被叫者使用'total'参数定义应该提取的总加仑水量。