SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Zealot
    Join Date
    Mar 2005
    Posts
    141
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Arrays and memory

    I have a function that creates an array using the push method and noticed that javascript has some sort of "memory" as far as arrays are concerned. Is there any way an unconnected function can access that array once it has been created? Thanks!

  2. #2
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    javascript has some sort of "memory" as far as arrays are concerned.
    Huh? See if these help:
    Code:
    var myArray = null;
    
    function createArray()
    {
    	myArray = [];
    	for(var i = 0; i < 3; ++i)
    	{
    		myArray.push(i * 10);
    	}
    }
    
    function displayArray(anArray)
    {
    	for(var i = 0, len = anArray.length; i < len; ++i)
    	{
    		alert(anArray[i]);
    	}
    }
    
    createArray();
    displayArray(myArray);
    Code:
    function createArray(length)
    {
            var newArray = [];
    	for(var i = 0; i < length; ++i)
    	{
    		newArray.push(i * 10);
    	}
    
    	return newArray;
    }
    
    function displayArray(anArray)
    {
    	for(var i = 0, len = anArray.length; i < len; ++i)
    	{
    		alert(anArray[i]);
    	}
    }
    
    function start()
    {
    	var myArray = createArray(3);
    	displayArray(myArray);
    }
    
    start();

  3. #3
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    function createArray()
    {
    	myArray = [12, 10, 3];  //Note: no 'var' keyword
    }
    
    function displayArray()
    {
    	for(var i = 0, len = myArray.length; i < len; ++i)
    	{
    		alert(myArray[i]);
    	}
    }
    
    createArray();
    displayArray();
    Note: there is no var keyword used in front of myArray. That means the variable will be created in the "global scope". The global scope is the area outside any function definitions. All functions can see things in the global scope.

  4. #4
    SitePoint Zealot
    Join Date
    Mar 2005
    Posts
    141
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks a lot. That last one did it for me!

  5. #5
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks a lot. That last one did it for me!
    The last one has the same effect as the first one, but the first one is clearer.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •