传递变量多种功能

问题描述:

我不知道这是否是重复或没有,但我无法找到关于该主题的帖子..传递变量多种功能

我想传递一个数组对象多种功能。我知道你通常做这样的事情:

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函数,任何人都可以帮忙吗?

+2

介绍如何调用'calcScore'。 – dfsq 2014-10-01 12:30:18

+0

当用户点击一个按钮'determineChoice'时,调用'getCpuChoice(cpuChoice)'并从那里'calcScore(p1_choice,cpuChoice,values)'调用 – user3164891 2014-10-01 12:33:17

+0

你会得到什么错误?你在这里给出的代码看起来很好。 – Neo 2014-10-01 12:33:52

试着改变你的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 
    } 
}