2012-07-12 164 views
0

我試圖讓這個函數在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循環函數的數組,還有一個過程。所以使用這個我應該能夠理解如何創建我的任務的下一部分。

+0

你想用這種方法完成什麼?目前還不清楚你想要做什麼,因爲它會返回一個在函數外部定義的全局變量。 – Austin 2012-07-12 01:10:56

+0

而你的論點「總數」甚至沒有被使用。 – Ruel 2012-07-12 01:17:57

+0

其學校工作,我試圖講一個故事,這是我的故事的一部分。我需要按照這個流程圖。在這個特定的部分,我需要有一個數字參數 - >數字函數 - >局部變量 - > while循環真正 - >數學 - >輸出 - >回while循環,或false off while循環 - >返回數字。我只是在學習功能,我很確定我不知道我在做什麼...:/ – Ezcaflowne 2012-07-12 01:35:17

回答

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並將其寫入到控制檯裏面那功能,然後用console.log(total)。請記住保留我在示例中刪除的total參數。

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

這將允許被叫定義應該提取的水的總加侖,使用‘總’的說法。