Include an “or” Operator in a JavaScript Switch Statement

I came across a situation where I needed a switch statement in JavaScript to do the exact same thing in multiple cases. For example:

switch (varAnimal)
{
   case ‘dog’:
   sameFunction();
   break;

   case ‘cat’:
   sameFunction();
   break;

   case ‘bird’:
   sameFunction();
   break;
}

While the above code works, if you have a long list of variables it is highly inefficient. To solve the problem I initially tried to use an “or” operator to try and test for the different values as you would do in an “if” statement. For example:

switch (varAnimal)
{
   case ‘dog’ || ‘cat’ || ‘bird’:
   sameFunction();
   break;
}

However this didn’t work. I found on a forum the below method which appears to accomplish what I was trying to do. It essentially lets you use an “or” operator to test for multiple cases which can save a lot of typing. For example:

switch (varAnimal)
{
   case ‘dog’: case ‘cat’: case ‘bird’:
   sameFunction();
   break;
}

Source: http://www.webdeveloper.com/forum/showthread.php?t=191879

How to find the length of an associative array in JavaScript

So this little tidbit took me a bit by surprise. The .length property does not work on associative arrays in JavaScript. It will return zero no matter how many elements are in the array. Below is a script I found that will correctly return the length of a JavaScript associative array.

 

associativeArrayLength = function(obj)
{
    var size = 0, key;
    for (key in obj)
        {
        if (obj.hasOwnProperty(key)) size++;
        }
    return size;
};

 

Source: http://stackoverflow.com/questions/5223/length-of-javascript-associative-array

Select random element from a Javascript Array

Need to select a random element from a javascript array? The process is fairly straightforward but I was not clever enough to figure it out on my own. First take a random number with Math.random() [which will return a random number between 0 and 1] then multiply this number by the length of the array. You then need to use Math.floor to round the number down to the nearest whole number and voila… you have a random element number. All of this can be included in the square brackets of the array to make more condensed/easy to read code.

For Example

randomElement = testArray[Math.floor(Math.random()*testArray.length)];

 

 

Source: http://www.webmasterworld.com/forum91/2245.htm