wilson1000
asked on
Set Global Array/Variable from inside a Javascript Function
Hi Experts,
Is there some big secret to setting array or variable values within a function for global access?
I'm using jQuery's getJSON() to return rows from our database. I then loop through and format the values there-in for display. my problem is I need to access this information later in the script.
I've omitted the var keyword before declaring the value and tested window.string to no avail
How can I achieve global scope for an array or indeed variable from within a function?
Thank you
Is there some big secret to setting array or variable values within a function for global access?
I'm using jQuery's getJSON() to return rows from our database. I then loop through and format the values there-in for display. my problem is I need to access this information later in the script.
I've omitted the var keyword before declaring the value and tested window.string to no avail
How can I achieve global scope for an array or indeed variable from within a function?
Thank you
You should declare that variable outside of the function.
Like:
<script type="javascript">
var myarr=new Array();
function myfunc(){
myarr[0]="first";
}
</script>
Like:
<script type="javascript">
var myarr=new Array();
function myfunc(){
myarr[0]="first";
}
</script>
ASKER
Thank you shinuq, would you clarify what a closure is please?
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Just for clarification, this is a perfectly acceptable solution:
window.myArray = ["Hello","World"]
...perhaps it is not clearly understood that, at the outermost level, vars are actually members of the window object and do not cause polution. You can check this for yourself with the following statements: var G = "!"; alert( window.G );
We will have to agree to disagree on that point.
No worries - glad to help.
Hope this helps