Regular expressions are a very powerful weapon for the developer if he can deals with all the pain of testing, debugging and learning the quirks of this matter.
I’m collecting some links to be red one day, when I’ll got time to dive more deeply in the argument:
Self explanatory code:
var T = {
getUnixTime: function() {
return parseInt(new Date().getTime().toString().substring(0, 10));
},
// format hh:mm:ss
getTime: function()
{
var d= new Date();
var time = new Array();
var hours = d.getHours();
time.push(hours);
var minutes = d.getMinutes().toString().length < 2 ? "0"+d.getMinutes() : d.getMinutes();
time.push(minutes);
var seconds = d.getSeconds().toString().length < 2 ? "0"+d.getSeconds() : d.getSeconds();
time.push(seconds);
return time.join(":");
}
}
Update: I’ve just discovered that
Syntax Highlighter code doesn’t work well with < > symbols in javascript code….
The code is self explanatory: you have an array and you want to know what index has the element “pippo” or “5”. So I extended the array object with prototype keyword to scan the array and to return the index if found, -1 otherwise.
var points = [56,12,36];
Array.prototype.getIndex = function(aVal)
{
for(item in this)
if(aVal == this[item])
return item;
return -1;
}
console.log(points.getIndex(36));
If you have Firefox or Safari (maybe in IE8 too, I dunno), watch at the console and you’ll see2 as result.
Since many libraries make use of the $ identifier, we need a way to prevent collisions between these names. jQuery provides a method called .noConflict() to return control of the $ identifier back to other libraries. Typical usage of .noConflict() follows the following pattern:
First, the other library (Prototype in this example) is included. Then, jQuery itself is included, taking over $ for its own use. Next, a call to
.noConflict() frees up $, so that control of it reverts to the first included library (Prototype). Now in our custom script we can use both libraries—but whenever we need to use a jQuery method, we need to use
jQuery instead of $ as an identifier.
// apply a class to all <a> which respect the filter selection.
$('a').filter(function() {
return this.hostname && this.hostname != location.hostname;
}).addClass('external');
I’ve found always useful using Bin-Blog’s dump function to explore the properties of an object or an array (like a PHP print_r) but now I’ve discovered that console.dir function does the same:
a = ['a', 1, true];
console.dir(a);
console.dir function will produce in output console this result:
>>> a = ['a', 1, true]; console.dir(a)
0 "a"
1 1
2 true
// returns 1 if defined, 0 otherwise.
function isDefined(anObj) {
switch(typeof(anObj)) {
case "string": if(anObj != "") return 1; else return 0;
case "undefined": return 0;
case "object": if(anObj != null) return 1; else return 0;
default: return 0;
}
}