Home >Web Front-end >JS Tutorial >Beautiful code snippets for JavaScript_javascript tips
Dynamically construct regular expressions
More flexible and clever number zero padding
Get the maximum and minimum value of the array
Generate beautiful random strings
Get timestamp
Relative to
var timeStamp = (new Date).getTime();
The following method is more convenient:
Convert to numeric value and round
String formatting
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
Copy code
Define and run functions
This is indeed the simplest technique, but it is also the most practical. Lays the foundation for JavaScript encapsulation.
Ternary operation
A function registration-calling mechanism
From CKEditor, I did the extraction.
'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