【问题标题】:Passing values among functions在函数之间传递值
【发布时间】:2011-08-08 20:17:23
【问题描述】:

我已经用 javascript 编写了一些代码,但是我不明白值是如何在函数之间传递的。抱歉查询,但我尝试搜索,并不太明白发生了什么。

这就是我想做的事情:

function check() {
    var x = "one";
    if (condition) 
    x = "two";
    //return x;
}

function compute() {
    maximum = 100;  //global
    var current = document.getElementById('test').value;
        var output = maximum/current;
        if(x == "one") Foo1();
        else Foo2();
}

function Foo1() {
    //code using value of ouput
}

var i=0;

function Foo2() {
    setTimeout(function () {
        //code
        i++;
        if (i < output) Foo2();
    }, 1000)
}

我希望x 的值转到compute() 并相应地在检查条件时转到Foo1Foo2,输出的值转到这些函数(Foo1Foo2)。

【问题讨论】:

  • 您的代码存在一些问题。您能否解释一下您要完成的工作,以便我们更好地解释您的代码?
  • check() 查看使用的是哪个浏览器,compute() 工作并输出值,这些值放在 Foo1() 或 Foo2() 中。 Foo2 用于递归生成动画。

标签: javascript function loops


【解决方案1】:

听起来你需要一些真正的 javascript 函数和参数基础知识。

这是一个简单的例子:

function step1() {
    var x = 3;   // This is a local variable.  It is not accessible anywhere outside
                 // this function unless it is passed as a parameter to a function call

    step2(x);    // Call step2, passing it a parameter
}

function step2(p) {
    // When this function starts, the parameter p will have whatever value
    // was passed in the function call.
    // In this particular example, it will initially have the value of 3.

    console.log(p);    // outputs 3

    p = p + 3;    // add three to the current value
    step3(p);     // call step3, passing it a parameter
}

function step3(r) {
    console.log(r);    // outputs 6
}

step1();    // call the first function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    相关资源
    最近更新 更多