www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 17

Thread: Global variable (array)

  1. #1
    Join Date
    Jan 2008
    Posts
    38

    Global variable (array)

    Hey

    I've found a script that eliminates empty elements from my array by pushing all the 'valid' elements into a new array. My problem is that I can't find a way to do things with the array outside of the function that creates it.


    My code:
    PHP Code:
    function convert(id)
      {
    resetOutput();


      var 
    output=document.getElementById('input').value;
      var 
    outputPREarray output.split("\n");
      var 
    outputALMOSTarray;

    function 
    cleanArray(actual){
      var 
    outputALMOSTarray = new Array();
      for(var 
    0i<actual.lengthi++){
          if (
    actual[i]){
            
    outputALMOSTarray.push(actual[i]);
        }
      }  
    }
    cleanArray('outputPREarray');

      var 
    outputarray outputALMOSTarray;
      var 
    outputLength outputarray.length;
      var 
    totalElements outputLength -1;


    //The rest of the script follows 

    'input' is the textarea containing the text, and 'output' is the variable that holds this data (I know I could shorten this but it works and the rest doesn't; one thing at a time). 'outputPREarray' is the first "raw" array and 'outputarray' is the array I want to end with that doesn't contain any empty elements. 'outputALMOSTarray' is just something I invented to be a global variable.

    Can anyone think of a way that I can use the new array? Easiest way to test is for a textbox that displays 'outputLength' - IE's error console thing complains that 'outputLength' is null at the moment.

    Many thanks in advance

    -Nut


    [[PS. The original array cleaner can be found here. Near the top, second post by user CMS, second solution.]]

  2. #2
    Join Date
    Jun 2007
    Posts
    667
    Quote Originally Posted by swnut View Post
    Can anyone think of a way that I can use the new array?
    The simplest thing is to declare the array without using var, although an object-orientated solution would be preferable.
    Y_U U_G_A_E_U_ B_S_A_D_

  3. #3
    Join Date
    Sep 2009
    Location
    London
    Posts
    51
    Any variable declared within a function and without a 'var' has a global scope. Therefore remove the 'var' from the array that you want to access outside the function that declares it.

  4. #4
    Join Date
    Jan 2008
    Posts
    38
    Ah nuts, why didn't I see that before? Thank you for pointing that out guys.

    New issue though; The function works perfectly in Firefox but doesn't work at all in IE (as per bloody usual). The rest of the script after the above works as it did before I put this new function in to take out the empty elements, it just isn't taking them out in IE. Obviously the original array gets put through that function as there's no other link between the original array and 'outputarray' except through 'outputALMOSTarray' so it appears IE doesn't like it for some reason.

    Any ideas?

    Thanks again

  5. #5
    Join Date
    Sep 2009
    Location
    London
    Posts
    51
    Hi,

    Based on the code that you've originally posted it is unclear as what is this new issue. Please update your code.

  6. #6
    Join Date
    Jan 2008
    Posts
    38
    Pretty much what I've got up there but with 'var' taken out:

    PHP Code:
    function convert(id)
      {
    resetOutput();


      var 
    output=document.getElementById('input').value;
      var 
    outputPREarray output.split("\n");
      var 
    outputALMOSTarray;

    function 
    cleanArray(actual){
      
    outputALMOSTarray = new Array();
      for(var 
    0i<actual.lengthi++){
          if (
    actual[i]){
            
    outputALMOSTarray.push(actual[i]);
        }
      }  
    }
    cleanArray(outputPREarray);

      var 
    outputarray outputALMOSTarray;
      var 
    outputLength outputarray.length;
      var 
    totalElements outputLength -1;


    //The rest of the script follows 

    Thanks
    Last edited by swnut; 09-09-2009 at 05:50 PM.

  7. #7
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    a simpler and faster way:

    Code:
    outputarray =outputPREarray.filter(String);

  8. #8
    Join Date
    Sep 2009
    Location
    London
    Posts
    51
    are you calling cleanArray('outputPREarray'); from within the convert() function.

  9. #9
    Join Date
    Sep 2009
    Location
    London
    Posts
    51
    Why are you calling cleanArray('outputPREarray'); and passing outputPREarray as a string 'outputPREarray', isn't it an array variable, should it be like cleanArray(outputPREarray);

  10. #10
    Join Date
    Jan 2008
    Posts
    38
    rnd me:
    How can I represent null where "string" is in the line you posted? I tried a few things but all it keeps saying is that Doesn't Support This Property Or Method...


    tpircsavaj:
    Yes it will be called inside of convert() as removing the empty elements should be the first part of the process. The rest of the function deals with the array once it's arranged - it shouldn't have any bearing on this part of the process.

    I'd noticed my mistake with the quote marks in cleanArray('outputPREarray'); but forgot to edit what I'd given here, so I have to apologise for that. I've taken them out now.

    When I tested after taking the var out as mentioned a couple of posts ago I had already removed those quote marks so the problem still remains unfortunately.

  11. #11
    Join Date
    Sep 2009
    Location
    London
    Posts
    51
    Ok,

    I'm assuming that all the values in the array are strings. If so then loop through the outputPREarray, trim the value (remove white space) and test the length, if length == 0 then splice it. The splice function will remove the value and the index check it on-line for more info.

  12. #12
    Join Date
    Sep 2009
    Location
    London
    Posts
    51
    Ok,

    try this out, fully working html, tested on IE8/7 Google Chrome and FireFox.

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    	<head>
    		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    		<title>Untitled Document</title>
    	</head>
    	<body>
    		<textarea id="input" rows="6" cols="30"></textarea><br/>
    		<input type="button" value="Convert" onclick="convert()">
    	</body>
    	<script>
    		function convert()
    		{
    			try
    			{
    				//resetOutput();			
    				
    				var output = document.getElementById('input').value;
    				var outputPREarray = output.split("\n");
    				var outputALMOSTarray = new Array();
    				
    				function cleanArray(actual)
    				{
    					for (var i = 0, len=actual.length; i < len; i++) 
    					{
    						if(typeof actual[i] == 'undefined')
    						{
    							actual.splice(i,1);
    						}
    						else if (strTrim(actual[i]).length == 0) 
    						{
    							actual.splice(i,1);
    						}
    					}
    					
    					return actual;
    				}
    				
    				outputALMOSTarray = cleanArray(outputPREarray);
    				
    				var outputarray = outputALMOSTarray;
    				var outputLength = outputarray.length;
    				var totalElements = outputLength - 1;
    				
    				var str = '';
    				for(var idx=0, len=outputarray.length; idx<len; idx++)
    				{
    					str += outputarray[idx]+'\n';
    				}
    				alert(str+'outputLength='+outputLength);
    			}
    			catch(e)
    			{
    				alert('ERROR: convert()\n\n'+e.message);
    			}
    		}
    		
    		/**
    		 * Removes all white space characters from the string.
    		 * 
    		 * @param: {String} String to trim.
    		 * 
    		 * @return {String} Trimed string.
    		*/
    		function strTrim(strTrim) 
    		{
    			return strTrim.replace(/^\s+|\s+$/g, '');
    		}
    	</script>
    </html>

  13. #13
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    Quote Originally Posted by swnut View Post
    rnd me:
    How can I represent null where "string" is in the line you posted? I tried a few things but all it keeps saying is that Doesn't Support This Property Or Method...
    Code:
    outputarray =outputPREarray.filter(Number);
    for ie compat, add this anywhere before the line above
    Code:
    if (![].filter) { //from  http://developer.mozilla.org/en/docs...s:Array:filter
      Array.prototype.filter = function (fun) {var len = this.length;if (typeof fun != "function") {throw new TypeError;}
      var res = new Array;var thisp = arguments[1];for (var i = 0; i < len; i++) {if (i in this) {
      var val = this[i];if (fun.call(thisp, val, i, this)) {
      res.push(val);}}}return res;};
    }
    Last edited by rnd me; 09-10-2009 at 02:59 AM.

  14. #14
    Join Date
    Jan 2008
    Posts
    38
    Thanks guys


    rnd me:
    I'm still failing to put that in correctly. It still complains about not supporting the property/method even with both part included I'm using the latest (full) versions of FF and IE so there shouldn't be a problem with the version of Javascript they're using...

    tpircsavaj:
    Thanks, that works One thing, though, if there are two or more empty lines in the input next to each other then it removes the first one and skips the next (and gets rid of any more empties directly after that second one). To the best of my knowledge this is because when it splices the first one out the for loop skips to the next when i++ . I've tried passing the new array through the same funtion a second time (in theory if there's only 1 empty element left of those lines of 2+ then by going round a second time it should remove it, right?) and it seems that every 4 empty lines next to each other causes one to remain in the array after the second time through the function. Weird.

    Is there some way of making sure that the missed element is checked in the function? I tried to make it check i and if true i+1 and it claimed that "strTrim is undefined" in that error alert you added to it. Using your test page, without changing anything before or after the cleanarray() function, this is what I changed:

    PHP Code:
                    function cleanArray(actual)
                    {
                        for (var 
    0len=actual.lengthleni++) 
                        {
                            if(
    typeof actual[i] == 'undefined')
                            {
                                
    actual.splice(i,1);
                                if(
    typeof actual[i+1] == 'undefined')
                                {
    actual.splice(i+1,1);}
                            }
                            else if (
    strTrim(actual[i]).length == 0
                            {
                                
    actual.splice(i,1);
                                if (
    strTrim(actual[i+1]).length == 0
                                {
    actual.splice(i+1,1);}
                            }
                        }
                        
                        return 
    actual;
                    } 

    Thanks again guys!
    Last edited by swnut; 09-10-2009 at 04:18 PM.

  15. #15
    Join Date
    Sep 2009
    Location
    London
    Posts
    51
    Yes that's right, as the array is spliced the index changes and the code is not handling that.

    Here is the fixed version it should work fine now.
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    	<head>
    		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    		<title>Untitled Document</title>
    	</head>
    	<body>
    		<textarea id="input" rows="6" cols="30"></textarea><br/>
    		<input type="button" value="Convert" onclick="convert()">
    	</body>
    	<script>
    		function convert()
    		{
    			try
    			{
    				//resetOutput();			
    				
    				var output = document.getElementById('input').value;
    				var outputPREarray = output.split("\n");
    				var outputALMOSTarray = new Array();
    				
    				function cleanArray(actual)
    				{
    					var arrDelete = new Array();
    					var idx = 0;
    					for (var i = 0, len=actual.length; i < len; i++) 
    					{
    						if(typeof actual[i] == 'undefined')
    						{
    							arrDelete[idx++] = i;
    						}
    						else if (strTrim(actual[i]).length == 0) 
    						{
    							arrDelete[idx++] = i;
    						}
    					}
    					
    					var delIDX=0;
    					for (var i = 0, len=arrDelete.length; i < len; i++) 
    					{
    						actual.splice(arrDelete[i]-delIDX,1);
    						delIDX++;
    					}
    					
    					return actual;
    				}
    				
    				outputALMOSTarray = cleanArray(outputPREarray);
    				
    				var outputarray = outputALMOSTarray;
    				var outputLength = outputarray.length;
    				var totalElements = outputLength - 1;
    				
    				var str = '';
    				for(var idx=0, len=outputarray.length; idx<len; idx++)
    				{
    					str += outputarray[idx]+'\n';
    				}
    				alert(str+'outputLength='+outputLength);
    			}
    			catch(e)
    			{
    				alert('ERROR: convert()\n\n'+e.message);
    			}
    		}
    		
    		/**
    		 * Removes all white space characters from the string.
    		 * 
    		 * @param: {String} String to trim.
    		 * 
    		 * @return {String} Trimed string.
    		*/
    		function strTrim(strTrim) 
    		{
    			return strTrim.replace(/^\s+|\s+$/g, '');
    		}
    	</script>
    </html>

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