2013-11-29 71 views
0

我想保存函数的值,该函数将变量中的.xml文件中的随机值返回,并在每次更新新值时更新变量由函数生成。将函数的值保存到变量中,该变量返回随机值

为了说明:这是我的功能

function getNewValue() { 
return videos[Math.floor(Math.random() * videos.length)]; 
} 

我倒是希望保存将其在变量如“CurrentValue的”而生成的值,所以每次的功能被调用时,“CurrentValue的”改变所产生的价值。

喜欢的东西:

var currentValue; 
function getNewValue() { 
return videos[Math.floor(Math.random() * videos.length)]; 
currentValue = getNewValue(); 
} 

不需额外的工作,因为函数生成isn't老一新的价值..

什么想法?谢谢

+0

getNewValue永远不会到达,因为您在执行之前返回。 – davidkonrad

回答

2

应该

var currentValue; 
function getNewValue() { 
    currentValue =videos[Math.floor(Math.random() * videos.length)]; 
    return currentValue; 
} 

你正在返回的getNewValue函数之前的值被分配到currentValue

+0

这听起来很合理。我想在$('#currentVideoDiv')。html('Currently Playing:'+ currentValue);但它只是返回“function getNewValue()...我如何显示实际值? –

+0

看起来像你在某处调用'currentValue = getNewValue',你是否在做这样的事情 –

+0

你可以在这里看到更多我的代码:http ://stackoverflow.com/questions/20274897/get-the-current-value-of-a-function-which-returns-random-values-youtube-api会很好,如果你看看这个。同样的问题 –

0
var currentValue; 

function getNewValue() { 
    return videos[Math.floor(Math.random() * videos.length)]; 
} 

currentValue = getNewValue(); 

我更倾向于这样做,因为它至少对我来说更具可读性。调用getNewValue()并在里面设置变量并不能告诉我,当我将这个函数调用到其他地方时,我实际上正在设置currentValue变量。

+0

问题是,getNewValue()是从另一个函数中调用的,然后我想将值保存在一个变量中以知道哪个值已设置,我不想在currentValue中保存一个新的随机值后记 –