如何使用参数为变量的函数?

时间:2015-03-08 17:07:26

标签: javascript arrays function variables

我一直在做一个小项目来学习javascript的基础知识,但我遇到了一个我无法解决的错误。我做了一些研究,但无济于事。 我想要一个生成攻击的程序(作为一个笑话)。它从数组中随机选择一个参数' people'并加入阵列中的一个'进攻'。一切顺利,直到我决定将随机数发生器变成一个函数。在这一点上,它开始做一些奇怪的事情,比如在询问朋友的名字后停下来,将personGenerator分配给未定义的'。 这是我的代码:

<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的新手,所以我对此并不了解。请让您的答案易于理解。如果我在任何时候使用了错误的术语,请说。

谢谢, Reece C。

1 个答案:

答案 0 :(得分:1)

此结构在Javascript中不起作用:

//creates a randomizer function
var random = function (variable,subject){
    variable = subject[Math.floor(subject.length * Math.random())]
}

这不会改变传入的变量。相反,您应该从我们的函数返回新的随机值。

//creates a randomizer function
var random = function (subject){
    return subject[Math.floor(subject.length * Math.random())];
}

然后,你在哪里使用它:

var personGenerator = random(person);

至于为什么你的原始代码在Javascript中不起作用,这是因为Javascript没有真正的引用传递,你可以改变原始变量指向的方式。当你这样做时:

//creates a randomizer function
var random = function (variable,subject){
    variable = subject[Math.floor(subject.length * Math.random())]
}

random(personGenerator, person);

随机函数中的variable参数将包含函数调用时personGenerator变量的内容。但是,它将是一个单独的变量。所以,这样做:

variable = subject[Math.floor(subject.length * Math.random())]

仅更改local函数参数的值。它不会更改personGenerator的值。

相关问题