Custom Array-like objects
function Collection() {
var i = 0, len = arguments.length;
if (len == 1 && typeof arguments[0] == 'number') {
for (i; i < arguments[0]; ++i) {
this[i];
}
} else {
for (i; i < len; ++i) {
this[i] = arguments[i];
}
}
this.length = i;
}
Collection.prototype = new Array();
Collection.prototype.constructor = Collection;
Collection.prototype.toString = function () {return this.join()};
var arr = new Array(6);
var dc = new Collection(6);
arr.push('test');
dc.push('test');
console.debug(arr, 'Array');
console.debug(dc, 'Collection');
So far this is working in Chrome 9, Safari 5 and Firefox 3.6. I’ll update this as I test each new browser, biut it’s safe to say it wont work in IE6
Character Arrays
/*
Character Arrays
whilst this is a useless example
it demonstrates the use of a string
as a character array
*/
var foo = "this is a string";
for (var i = 0, len = foo.length; i < len; ++i)
console.log(foo[i]);
/*
Result:
t
h
i
s
i
s
a
s
t
r
i
n
g
*/
Short hand timestamp
/* Short hand timestamp As far as I know, this is the quickest shortest method to get the current timestamp */ +new Date;
Shortest conditional statement
/* Short hand conditional This is similar to Optional constructor arguments utilising right hand evaluation if left hand results in boolean true */ var foo = 2, bar; foo == 2 && (bar = 3); /* Can also be used to call functions conditonally */ foo == 2 && baz();
Object properties to Array
/*
Collecting object properties into
an Array
*/
var i = 0, arr = [];
var foo = {bar: "value bar", baz: "value baz"};
for(arr[i++] in foo)
/*
Result:
arr == ["bar", "baz"]
*/
Optional constructor arguments
/*
Setting object parameters
optionally in the constructor
bar is required, baz is optional
Note:
false or 0 will result in no value being
used. Better to use conditions in this case.
*/
function foo(bar, baz) {
this.bar = bar;
baz && (this.baz = baz);
}
foo.prototype = {
bar: "",
baz: ""
};
Function arguments with defaults
/*
Function with defaulted arguments
bar is required, baz is optional with a default
Note:
false or 0 will result in the default value being
used. Better to use conditions in this case.
*/
function foo(bar, baz) {
baz = baz || 'default value';
}