将变量传递给MULTIPLE函数



我不确定这是否重复,但我找不到关于这个主题的帖子。。

我正试图将一个数组对象传递给多个函数。我知道你通常会这样做:

function name(values){
    var values ={
        name : "John",
        lastname: "Doe"
    }
    sayHello(values){
        alert(values.name);
    }
}

但在这种情况下,这是行不通的。数组对象的传递方式与上面的代码片段类似,并且运行良好。但当我以后想在另一个函数中使用它时,我会得到一个错误,即变量没有定义。这是我的代码:

function createValues(values){
    var values = {left:     (Math.floor((Math.random()*10)+1)),
                  right:    (Math.floor((Math.random()*10)+1)),
                  bottom:   (Math.floor((Math.random()*10)+1)),
                  top:      (Math.floor((Math.random()*10)+1))
            };  
    displayValues(values);
}
function displayValues(values){
     document.getElementById("left").innerHTML    = values.left;
     document.getElementById("right").innerHTML   = values.right;
     document.getElementById("bottom").innerHTML  = values.bottom;
     document.getElementById("top").innerHTML     = values.top;
     // The values are getting passed to this function
 }
function calcScore(p1_choice, values){
    if(p1_choice == "left"){
        score += values.left
        // Can't access the variables here
    }
}

单击按钮后,另一个函数会调用calcScore函数。我试图让价值观全球化,但这无济于事。我不知道如何将变量传递给calcScore函数,有人能帮忙吗?

尝试将calcScore函数更改为此

function calcScore(p1_choice){
    var values = {left:     (document.getElementById("left").innerHTML),
                  right:    (document.getElementById("right").innerHTML),
                  bottom:   (document.getElementById("bottom").innerHTML),
                  top:      (document.getElementById("top").innerHTML)
        }; 
    if(p1_choice == "left"){
        score += values.left
        // Can't access the variables here
    }
}

最新更新