Archive for August 10, 2007

How to Remove All Elements From a JavaScript Array

Posted in JavaScript on August 10, 2007 by Joey

To remove all the elements from a JavaScript array, simply set the array length to 0, as shown in the following example:

var aryTest = [1,2,3,4];
document.write(aryTest.length);

aryTest.length = 0;
document.write(aryTest.length);

Related articles:
JavaScript Arrays Summary and Reference
JavaScript Array length Property

JavaScript to Get Number of Days in a Month

Posted in JavaScript on August 10, 2007 by Joey

At work recently the need came up to determine the number of days in a month for a given month and year. This can be accomplished by creating a date object for the given month and year. Then do a while loop. In each iteration of the loop, set the day of the month, starting with 29, which is one more than the fewest days that can occur in a month. After setting the day, check if setting that day changed the month. If it did, then the number of days has been found. Otherwise, the loop iterates again.

For example, for September of 2007, the loop would use setDate() to set a date for September 29th. After doing this, the month would still be 8 (JavaScript dates are zero-relative). The loop would run again. setDate() would set the 30th and the month would still be 8. The loop would run again. setDate() would set the 31st. Since there is no 31st in September, setDate() actually sets October 1st, thus making the month 9. Since the month has changed, we know there are 30 days in September.

Code:

var intMonth = 7;//given month
var intYear = 2007;//given year

var dteMonth = new Date(intYear,intMonth);//
var intDaysInMonth = 28;//the fewest number of days in a month
var blnDateFound = false;//Set a variable to check on the while loop

while (!blnDateFound)
{
dteMonth.setDate(intDaysInMonth+1);//create the next possible day
var intNewMonth = dteMonth.getMonth();//new month date

if (intNewMonth != intMonth)//if the month has changed
  blnDateFound = true;
else
  intDaysInMonth++;
}
document.write(intDaysInMonth);