我一直在工作一個小項目來學習javascript的基礎知識,但我遇到了一個我無法修復的錯誤。我做了一些研究,但無濟於事。 我想要一個產生犯罪的程序(作爲笑話)。它從數組'people'中隨機選擇一個參數,並將其與陣列'進攻'中的一個相加。一切都很順利,直到我決定讓隨機函數變成一個函數。此時它開始做奇怪的事情,比如詢問朋友的名字後停下來,將personGenerator分配給'undefined'。 這裏是我的代碼:如何使用參數爲變量的函數?
<script>
//this is plonker base
//creates a variable that will start the game
var start = confirm("Are you sure want to participate in plonker base alpha?")
//starts and loops the game
if(start==true){
//asks for another person's name
var person1 = prompt("Please name one of your best friends.")
}
//creates a randomizer function
var random = function (variable,subject){
variable = subject[Math.floor(subject.length * Math.random())]
}
while(start==true){
//creates array 'person'
var person = ["You are ","Your mum is ","Your dad is ", "The world is ", (person1 + " is ")]
var personGenerator
random(personGenerator,person)
//creates an array 'offence'
var offence = ["an idiot!",
"a complete pysco!!!",
"a smelly, worthless peice of junk!",
"a whale re-incarnated that looks like a squirrel!",
"a dumb pile of dirt that has the misfortune of seeing itself in the mirror once in a while!",
"a complete and utter plonker!",
"a dumbo!",
"a right dufus!!!",
"a pile of rabbit dung!",
"an intelligant, good looking king being... Did I mention - it's opposite day!",
"a bum-faced rat!!!",
"a fat, lazy oaf!",
"a blobfish look-alike!!!!!",
"a lump of toenail jelly!"]
var offenceGenerator = offence[Math.floor(offence.length * Math.random())]
//gives out the offence
alert(personGenerator + offenceGenerator)
}
{
alert("What a plonker!")
}
</script>
我是新來的JavaScript,所以我不很瞭解。請讓你的答案容易理解。如果我在任何時候使用了錯誤的術語,請說。
感謝, 里斯C.
你不需要做'if(start == true)'。你可以做'if(start)',因爲'start'是一個布爾值。 – TheDude 2015-03-08 17:12:29
這段代碼有很多語法錯誤,在語句結尾處有很多缺少的分號。 – ataravati 2015-03-08 17:13:33
有人告訴我,除非您使用的是舊版本的JavaScript,否則您不需要在末尾放置分號?他們做什麼,因爲我的JavaScript編碼大部分工作正常,沒有他們...... – 2015-03-08 17:17:12