首页 > 语言 > JavaScript > 正文

JavaScript的漂亮的代码片段

2024-05-06 14:38:50
字体:
来源:转载
供稿:网友

 动态构建正则表达式

代码如下:
 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封装的基础。

三元运算

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选