Home  >  Article  >  Web Front-end  >  Beautiful code snippets for JavaScript_javascript tips

Beautiful code snippets for JavaScript_javascript tips

WBOY
WBOYOriginal
2016-05-16 17:32:441003browse

Dynamically construct regular expressions

Copy code The code is as follows:

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

Copy code The code is as follows:

function prefixInteger(num, length) {
return (num / Math.pow(10, length)).toFixed(length).substr(2);
}

Get the maximum and minimum value of the array

Copy code The code is as follows:

Math.max.apply(Math, [1,2 ,3]) //3
Math.min.apply(Math, [1,2,3]) //1

Generate beautiful random strings

Copy code The code is as follows:

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:

Copy code The code is as follows:

var timeStamp = Number(new Date);

Convert to numeric value and round

Copy code The code is as follows:

var result = '3.1415926' | 0; // 3


String formatting

Copy code The code is as follows:

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
The code is as follows: format('{0}.facebook.com/{1}', 'www', 'login.php'); //-> www. facebook.com/login.php


Exchange the values ​​of two variables

Copy code

The code is as follows:var foo = 1;var bar = 2 ;
foo = [bar, bar=foo][0];



RegExp Looping

Copy code

The code is as follows:String.prototype.format = function ( /* args * / ) { var args = arguments;
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

Copy code The code is as follows:

( function() {
// do something
} )();

This is indeed the simplest technique, but it is also the most practical. Lays the foundation for JavaScript encapsulation.

Ternary operation

Copy code The code is as follows:

var some = con1 ? val1 :
con2 ? val2 :
con3 ? val3 :
defaultVal;

A function registration-calling mechanism

From CKEditor, I did the extraction.

Copy code The code is as follows:

( 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

Copy code The code is as follows:

var something = 'xxxx';
console. log( true && something ); //-> 'xxx';
console.log( false && something ); //-> false
console.log( true || something ); // - > true
console.log( false || something ); //-> something
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn