Dynamically construct regular expressions
new RegExp( Expr.match[ type ].source ( /(?![^[]*])(?![^(]*))/.source) )
from sizzle, when dynamically building regular expressions, this avoids character escaping .
More flexible and clever number zero padding
function prefixInteger(num, length) {
return (num / Math.pow(10, length)).toFixed(length).substr(2);
}
Get the maximum and minimum value of the array
Math.max.apply(Math, [1,2 ,3]) //3
Math.min.apply(Math, [1,2,3]) //1
Generate beautiful random strings
Math.random().toString(16).substring (2); //8-bit
Math.random().toString(36).substring(2); //16-bit
Get timestamp
Relative to
var timeStamp = (new Date).getTime();
The following method is more convenient:
var timeStamp = Number(new Date);
Convert to numeric value and round
var result = '3.1415926' | 0; // 3
String formatting
function format(format) {
if (! FB.String.format._formatRE) {
FB.String.format._formatRE = /({[^}^{] })/g;
}
var values = arguments;
return format.replace(
FB.String.format._formatRE,
function(str, m) {
var
index = parseInt(m.substr(1), 10),
value = values[index 1]; ;
}
);
}
Use:
Copy code
Exchange the values of two variables
Copy code
foo = [bar, bar=foo][0];
RegExp Looping
Copy code
return this.replace(
/{(d )}/g,
function (full, idx) {
return args[idx];
} )
}
'Hello {0}, How{1}'.format( 'Bob', ' you doin');
// => Hello Bob, How you doinhttp://mazesoul.github.com/ Readability_idioms_and_compression_tolerance/#31.0
Define and run functions
( function() {
// do something
} )();
This is indeed the simplest technique, but it is also the most practical. Lays the foundation for JavaScript encapsulation.
Ternary operation
var some = con1 ? val1 :
con2 ? val2 :
con3 ? val3 :
defaultVal;
A function registration-calling mechanism
From CKEditor, I did the extraction.
( function() {
var fns = [ ];
// Convert objects whose attributes can be accessed by subscripts into arrays
// Note that DOMNodeList will fail under IE
function toArray( arrayLike, index ) {
return Array.prototype.slice .call( arrayLike, index || 0 );
}
window.Util = {
'addFunction' : function( fn, scope ) {
return fns.push( function(){
return fn.apply( scope || window, arguments );
} ) - 1;
},
'removeFunction' : function( index ) {
fns[ index ] = null;
},
'callFunction' : function( index ) {
var fn = fns[ index ];
return fn && fn.apply( window, toArray( arguments, 1 ) );
}
};
} )();
// Application scenario
var fnId;
// In the closure, add a function that can be called globally
( function( ) {
fnId = Util.addFunction( function( msg ) {
alert( msg );
} );
} )();
// Call
Util.callFunction( fnId, 'Hello, World' ); //-> 'Hello,World';
Short circuit operation
var something = 'xxxx';
console. log( true && something ); //-> 'xxx';
console.log( false && something ); //-> false
console.log( true || something ); // - > true
console.log( false || something ); //-> something