[英]How do I set a variable in a function using Javascript or jQuery
I need to move the data out of HTML code and load it on demand. 我需要将数据移出HTML代码并按需加载。
I need to do something like this: 我需要做这样的事情:
function processData( data )
{
if ( data.length===0 )
{
data = get data from server using Ajax or even...
data = [['2011-06-01',1],['2011-06-02',3]] ; // just for educational purposes
}
else go do stuff with data ;
}
storeData = [] ;
processData( storeData ) ; // first time storeData doesn't contain any data
processData( storeData ) ; // now storeData contains data
I can't figure out how to stuff the data from within the function. 我不知道如何从函数中填充数据。 Is there a way of accomplishing this?
有没有办法做到这一点?
function processData()
{
if ( storeData.length===0 )
{
storeData = get data from server using Ajax
}
else go do stuff with storeData ;
}
storeData = [] ;
processData( storeData ) ; // first time storeData doesn't contain any data
processData( storeData ) ; // now storeData contains data
storeData is a global anyway. storeData无论如何都是全局的。 When you specify
processData( data )
you are doing what's called a pass by value. 当指定
processData( data )
您正在执行所谓的按值传递。 Basically your making a copy of the data. 基本上,您是在复制数据。 Once the program exits the function, the copy is lost to garbage collection.
程序退出功能后,副本将丢失到垃圾回收中。 An alternative would be to pass by reference, but because it's a global anyway (declared outside the function) there's little point.
另一种选择是通过引用传递,但是因为无论如何它都是全局的(在函数外部声明),所以没有什么意义。
read here 在这里阅读
http://snook.ca/archives/javascript/javascript_pass http://snook.ca/archives/javascript/javascript_pass
It might help to know more concrete details since it seems like you might be going about your task in an unusual way. 了解更多具体细节可能会有所帮助,因为您似乎可能以一种不同寻常的方式来完成任务。 There may be a better way of accomplishing what you want.
可能会有更好的方法来完成您想要的。
Have you just tried something as simple as: 您是否尝试过以下简单的操作:
function processData( data )
{
...
return data;
}
storeData = [] ;
storeData = processData( storeData ) ; // first time storeData doesn't contain any data
storeData = processData( storeData ) ; // now storeData contains data
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.