JavaScript的漂亮的代码片段

  动态构建正则表达式

  

复制代码 代码如下:

  new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) )

  来自sizzle,动态构建正则时,这样做避免了字符转义。

  更灵活和巧妙的数字补零

  

复制代码 代码如下:

  function prefixInteger(num, length) {

  return (num / Math.pow(10, length)).toFixed(length).substr(2);

  }

  取数组的最大和最小值

  

复制代码 代码如下:

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

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

  产生漂亮的随机字符串

  

复制代码 代码如下:

  Math.random().toString(16).substring(2); //8位

  Math.random().toString(36).substring(2); //16位

  获取时间戳

  相对于

  var timeStamp = (new Date).getTime();

  如下方式更方便:

  

复制代码 代码如下:

  var timeStamp = Number(new Date);

  转换为数值并取整

  

复制代码 代码如下:

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

  字符串格式化

  

复制代码 代码如下:

  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];

  if (value === null || value === undefined) {

  return '';

  }

  return value.toString();

  }

  );

  }

  使用:

  

复制代码 代码如下:

  format('{0}.facebook.com/{1}', 'www', 'login.php');

  //-> www.facebook.com/login.php

  交换两个变量的值

  

复制代码 代码如下:

  var foo = 1;

  var bar = 2;

  foo = [bar, bar=foo][0];

  RegExp Looping

  

复制代码 代码如下:

  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

  定义即运行函数

  

复制代码 代码如下:

  ( function() {

  // do something

  } )();

  这确实是最简单的技巧,但也是最实用的技巧。 奠定了JavaScript封装的基础。

  三元运算

  

复制代码 代码如下:

  var some = con1 ? val1 :

  con2 ? val2 :

  con3 ? val3 :

  defaultVal;

  一种函数注册-调用机制

  来自CKEditor,我做了提取。

  

复制代码 代码如下:

  ( function() {

  var fns = [];

  // 将可用下标访问属性的对象转换成数组

  // 注意,IE下DOMNodeList会失败

  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 ) );

  }

  };

  } )();

  // 应用场景

  var fnId;

  // 在闭包中,添加一个可供全局调用的函数

  ( function() {

  fnId = Util.addFunction( function( msg ) {

  alert( msg );

  } );

  } )();

  // 调用

  Util.callFunction( fnId, 'Hello, World' ); //-> 'Hello,World';

  短路运算

  

复制代码 代码如下:

  var something = 'xxxx';

  console.log( true && something ); //-> 'xxx';

  console.log( false && something ); //-> false

  console.log( true || something );  // -> true

  console.log( false || something );  //-> something