Archive

Posts Tagged ‘loop’

PHP foreach Equivalent In JavaScript

March 31st, 2009 No comments

If you are familiar with PHP you will have come across the forloop at some point. When learning JavaScript it is important to remember that it also has the ability to do the equivalent of the PHP forloop.

The following snippet shows the creation of an array of things that can’t be referenced by a normal for loop due to the odd numbering of the keys.

var arrThings= new Array();
 
arrThings[3] = 'thing 1';
arrThings[42] = 'thing 2';
arrThings[47] = 'thing 3';
arrThings[32] = 'thing 4';
 
var output = '';
 
for ( var thing in arrThings ) {
 output += arrThings[thing];
}
alert(output);

The variable thing is now the iterator and will iterate through each element of the array. By using this code you no longer have to include code that thinks about the length of the array.

Categories: JavaScript Tags: , , , , ,

Loop Through All Files In A Directory With DOS Batch

September 16th, 2008 No comments

DOS Batch is the Windows equivalent of shell scripting and can be used to perform all sorts of different actions. Anything that you type into a DOS prompt on a Windows machine can be used in a bat file to quickly do something that you would otherwise have to repeat many times over.

To create a bat file just make a file and give it the extension "bat". If you run a DOS prompt and navigate to the directory that the bat file exists in you can type the name of the file to get it to do certain actions. If you called your file "action.bat" you can run it by typing "action" or "action.bat".

Starting with a simple example, if you want to print the contents of a file to screen then you need the type command, followed by the file.

type file.txt

However, this puts a lot of rubbish on the screen. If you wanted to create a backup of that file then you would write the following.

type file.txt > file_back.txt

This takes the contents of one file and puts it in another.

To loop through every file in a directory you need to use the following line.

FOR %%i IN (*.*) DO echo %%i

This code will loop through the contents of a directory and print out each file name to screen. This will also list the bat file that you put in the directory so another solution might be to run the bat file from the directory above and use the following code.

FOR %%i IN (directory\*.*) DO echo %%i

The following snippet of code takes the previous example and does something useful. It loops through the directory and puts every file name that it finds into a file called list.txt.

FOR %%i IN (directory\*.*) DO echo %%i >> list.txt

The >> symbol will append any content to the file, so for every iteration of the loop the list.txt file gets one line bigger, until all of the files have been listed. In an example directory the following would be seen in the list.txt file.

directory\directory.html
directory\match.xls
directory\directory.xls
directory\file.txt
directory\file_back.txt

Categories: DOS Tags: , , , , ,

JavaScript Simple Loop Optimisation

February 18th, 2008 No comments

When writing JavaScript applications I normally write for loops like this.

for(var i = 0;i < elements.length;++i){
  // loop...
}

There isn’t anything wrong with this, but it is not an efficient way of doing things. All it takes is a little knowledge of what the for loop does every time it runs. The loop can be split into three sections like this.

for(/*initialise loop*/;/*test loop parameter*/;/*run command every loop*/){}

The first section initialises the loop, this allows you to set up counters that will be used for the duration of the loop and beyond. The second section is used to test for certain conditions at the start of each iteration of the loop, if the result is true then the loop continues, if it is false it stops. The third section is also run at the start of each iteration of the loop and is used to carry out a small calculation, like the incrementing of the loop counter. The third parameter isn’t actually required and you could get by doing something like this.

for(var i = 0;i < elements.length;){
  ++i;
  // loop...
}

An excelent way of speeding up any loop is by setting up more than one variable within the initialisation section of the loop. If you are counting through the items in an array you will have to find out the length of the array every time you run through the loop. A more efficient way is to find out what the length of the array is at the start, store this value in a variable and then test the variable. Here is an example.

for(var i = 0,j = items.length;i<j;++i){
   // loop
}

Here the length of the items array is stored as the variable j, which is then used to test against the loop counter i. This means you only need to find the length of an array once, not every time you run through the loop.

Categories: JavaScript Tags: , , , ,

For Loop Debugging In JavaScript

January 3rd, 2008 1 comment

The for loop in JavaScript can be used to iterate through all items in an array or properties of an object. This makes looping through any object or array very easy. As in the following example that printing out all items in an array.

var count = '';
var numbers = new Array(3);
numbers[0] = 42;
numbers[1] = 13;
numbers[2] = 73;
for(i in numbers){
  count += numbers[i]+' ';
}
alert(count);

The three main objects to do with a JavaScript are navigator, window and document. Although window is part of navigator and document is part of window. So to print off all information to do with a browser you can do the following. Note that some items in window and document can cause JavaScript to crash in some browsers so some error detection is included here.

var html = '<table border="1">';
html += "<tr><th>Navigator Properties</th><th>Value</th></tr>";
for(i in navigator){
  html += "<tr><td>" + i + "</td><td>" + navigator[i] + "</td></tr>\n";
}
html += "<tr><th>Window Properties</th><th>Value</th></tr>";
for(i in window){
  try{
    html += "<tr><td>" + i + "</td><td>" + window[i] + "</td></tr>\n";
  }catch(err){
    // skip item
  }
}
html += "<tr><th>Document Properties</th><th>Value</th></tr>";
for(i in document){
  try{
    html += "<tr><td>" + i + "</td><td>" + document[i] + "</td></tr>\n";
  }catch(err){
    // skip item
  }
}
html += '</table>';
var div = document.getElementById('test');
div.innerHTML = html;

This produces the output.

Navigator Properties Value
appCodeName Mozilla
appName Netscape
appVersion 5.0 (Windows; en-GB)
language en-GB
mimeTypes [object MimeTypeArray]
platform Win32
oscpu Windows NT 5.1
vendor
vendorSub
product Gecko
productSub 20071127
plugins [object PluginArray]
securityPolicy
userAgent Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11
cookieEnabled true
onLine true
javaEnabled function javaEnabled() { [native code] }

Note : Table cut off for brevity.

Internet Explorer will label everything with the value of that property or as an "object" regardless as to the object type. Firefox, Safari and Opera will give more meaningful output with a number of different object types. A couple of object types to watch out for are as follows:

  1. [native code] : This is native JavaScript code. For example, in the document object you will see a property called write with the value of function write() { [native code] }. This is the document.write function that can be used to write output to the browser.
  2. [object HTMLCollection]: This is a collection (or array) of HTML objects. For example, every link in the document body is kept in the links property.
  3. [object Window]: For the frames property this object is an array of windows, one object for each frame. This object type is called [object WindowCollection] in Opera.
  4. [object PluginArray]: This is an array containing information about the plugins available in the browser which is not available in Internet Explorer. To find plugins for Internet Exploer you will need to use VBScript. Firefox has additional untility property and functions. If you wanted to know is the user had flash installed then you could use this array to look for the Shockwave Flash plugin. Each plugin object has a property of name that you can use to see what the plugin is.

To find the values of any inner object you can use the dot notation in the same array as before. For example, to see all of the plugins available for your browser use the following code (not in IE). As each plugin has a name property this has been included to detail the name of each plugin.
html += "<tr><th>Plugins</th><th>Value</th></tr>";
for(i in navigator.plugins){
  html += "<tr><td>" + i + "</td><td>" + navigator.plugins[i] + " " + navigator.plugins[i].name + "</td></tr>\n";
}

To find all of the available links on a page you can use the document.links array. As each link should have a title tag this can be referenced use the title property of each link.
html += "<tr><th>Plugins</th><th>Value</th></tr>";
for(i in document.links){
  html += "<tr><td>" + i + "</td><td>" + document.links[i] + " " + document.links[i].title + "</td></tr>\n";
}