www.webdeveloper.com
Results 1 to 12 of 12

Thread: Return array contents from a function

  1. #1
    Join Date
    May 2010
    Posts
    23

    Return array contents from a function

    Hi,
    I'm having real trouble with this, hopefully someone can help. The basic structure I have is:

    Code:
    function {
    declare an array (returnArray);
    do this, do that;
    return returnArray;
    }
    
    document.write('The array elements are ' + returnArray);
    The problem is that I just constantly get returnArray undefined! Please help?

  2. #2
    Join Date
    May 2010
    Posts
    51
    this is due to the scope of the variable:
    Code:
    function thisHasVariable(){
      var Variable=0;
      Variable++;
      alert(Variable); // will say 1
      return Variable;
    }
    alert(Variable); // undefined Variable only exist within {} of the thisHasVariable function
    alert(thisHasVariable());// will say 1 because the function returns that value
    var globalVar=22; // this can be used anywhere because it's declared not within {}

  3. #3
    Join Date
    May 2010
    Posts
    23
    Thanks for the reply. So how do I return the contents of an array created within a function? This is for a college assignment and so I have to use code already defined.

    So the sturcture is:

    Code:
    define an array and elements (we'll call it newArray)
    
    call function {
    define a new array (called returnArray)
    copy the content of newArray to returnArray
    swap some elements about
    return returnArray
    }
    
    write the content of returnArray to the screen.
    The problem I have is that returnArray is always undefined. I understand that it is only valid inside the function, but then we use return to be able to access the array outside of the function.

    What is going wrong? Thanks!

  4. #4
    Join Date
    Feb 2010
    Location
    Amsterdam
    Posts
    174
    Code:
    <html>
    <head></head>
    <body>
    
    <script type="text/javascript">
    //define an array and elements (we'll call it newArray )
    var newArray = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']; // im comming to getcha
    
    // document.write(newArray); test, this works
    
    function whatsInAName(arr){
    //define a new array (called returnArray)
    var returnArray = [];
    //copy the content of newArray to returnArray
    returnArray = arr.slice();
    //swap some elements about
    returnArray = returnArray.sort(function(a, b){return Math.round(Math.random())}); // swap some elements via the sort function
    return returnArray;
    }
    
    document.write(whatsInAName(newArray)); //write the content of returnArray to the screen.
    
    </script>
    </body>
    </html>

  5. #5
    Join Date
    May 2010
    Posts
    23
    OK, this is what I have and it works. But, I want to write the elements of returnArray to the screen. All I have done here is to copy the elements of returnArray back to unsortedArray which was declared outside the function.

    So although it's work, it's still not exactly as per spec

    Code:
    function bubbleSort(arrayToSort) 	{
    			
    var length = arrayToSort.length;
    var returnArray = new Array(length);
    array
    for (var i = 0; i < length; i = i + 1)
    {
    	returnArray[i] = arrayToSort[i];
    }
    		
    var temp;
    for (x = 0; x < length; x = x +1)
    {
    	for (var e = 0; e < (length - 1); e = e + 1)
    	{
    		if (returnArray[e] > returnArray[e+1])
    		{
    			temp = returnArray[e+1];
    			returnArray[e+1] = returnArray[e];
    			returnArray[e] = temp;
    			finished = false;
    		}
    	}
    }
    unsortedArray = returnArray;
    }
    		
    var unsortedArray = [9,7,2,10,1,4,8,6,5,3];
    		
    document.write('Unsorted array ' + unsortedArray + '<BR>');
    bubbleSort(unsortedArray);
    document.write('Sorted array ' + unsortedArray);
    As you can see, returnArray is declared inside the function. So basically the goal is for the last line of the program to be:

    Code:
    document.write('Sorted array ' + returnArray);
    Thanks for your help.

  6. #6
    Join Date
    May 2010
    Posts
    51
    I think you missed the point of a function returning a value.
    function someFunction(){
    return "Hello";
    }
    var sayHello = someFunction();
    alert(sayHello);
    Here the function returns a string you can return an array and assign it to another variable or you can just write out the return value without assigning it to another variable first:
    alert(someFunction());

    in your case:
    Code:
    document.write('Sorted array ' + bubbleSort(unsortedArray).join())
    Your assignment did not specify that the function should alter the value of newArray (see post 3) but it did specify it should return an array which it doesn't now.

    leave out the line:
    unsortedArray = returnArray;

    And replace it with .... you think about that one for 30 minutes (return something ....).

    I think it's a bad idea to have us do your homework but don't mind helping you along.
    Last edited by amsterdamharu; 05-21-2010 at 11:33 AM.

  7. #7
    Join Date
    May 2010
    Posts
    23
    So I'm still somewhat confused, but at least it's working as it should now. Bit of trial and error really.

    You're quite right in not giving me the answer, that's not what I wanted. I wouldn't have learned anything to just copy it from you.

    If you have the time (and the inclination), could you just explain why I can't just write the thing the function returns?

    what my program does now is

    Code:
    document.write('Sorted array ' + bubbleSort(unsortedArray));
    What I was always doing was putting return returnArray in the function since I first made the program, but it never worked (because of fault below), so I then removed it thinking it was wrong. I don't understand why I can't just use:

    Code:
    document.write(returnArray);
    This is what confused me, looks like I can't do this?

    Thanks very much for all your help, it is appreciated!

  8. #8
    Join Date
    May 2010
    Posts
    51
    I think you got it now. The function bubbleSort returns the value of returnArray when you call it.

    The variable returnArray only exist inside the bubbleSort function, this has todo with scope. So when you ask for returnArray outside of the bubbleSort function it will be undefigned.

    Declaring a variable: var myvar=...
    Scope of the variable is between the {} of a function (not an if statement)

    Code to demonstrate:
    Code:
    var i=0;
    alert("global i is now:" + i);
    function test(){
     var i=22;// declaring a variable called i within the function scope 
     alert("the other variable i within the function scope is:" + i);
     var localVar="exist only within the function";
    }
    test();
    alert("now outside the function, i is now the global i:" + i);
    
    // ie never shows this alert because lovalVar is undevined
    alert("localVar does not exist here, it is undefigned:" + !!localVar);
    I like to help people learn, good to see you are here to learn.

  9. #9
    Join Date
    May 2010
    Posts
    23
    Thanks for your help so far. So another question I have is that if I had a loop counter (for example) declared inside the function, how would I make that accessible outside of the function? So that I could write the counter value to the screen after the function 'exits'.

    Not the answer please, just a helping hand

  10. #10
    Join Date
    May 2010
    Posts
    51
    you could return just the counter or if you need to return multiple values return an object:
    I will give you an example because this is quite strange in syntax if you have to look it up.
    Code:
    function someFunction(){
       .... some code
       return {counter:vaueOfCounter, array:valueOfArray}
    }
    var obj=someFunction(); // assign a variable named obj to the return value of the function
    alert(obj.counter);// value of the counter
    alert(obj.array); // value of the array
    There are 2 other solutions:
    http://javascript.about.com/library/blmultir.htm
    1. use global variables (not a good one) global variables can be used anywhere in the script
    2. return an array, could be ok but you have to know the index and doesn't read so easily as the object

  11. #11
    Join Date
    May 2010
    Posts
    23
    Just sounds a whole lot easier to declare a variable outside of the function for something as simple as a counter?

    Or, use document.write() just before the loop exits to display the counter?

  12. #12
    Join Date
    May 2010
    Posts
    51
    No, scoping variables is very important. See my previous post on the variable named i. Declaring a global variable when only used in a counter or loop will confuse other functions when starting a loop. And the variable stays in memory even though you never use it.

    A script might be simple but used as an include on many pages (<script src="includeThis.js") then using global variables run the risk of overwriting other variables or your global gets overwritten.

    In your example it might not make any difference but you might as well do it right, pretend this is part of some major website. If you do it like that you will learn not to use globals casually.

    As for document.write() that could work but I am not sure if your assignment is to get the value of the counter in the script or show it to the user. document.write() will show it to the user but after the function exits it's not available in script anymore.
    Last edited by amsterdamharu; 05-22-2010 at 09:10 AM.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles