JavaScript 实用代码技巧与常见陷阱解析

作者:代码拾荒

时间:2026-10-27

浏览:341

本文整理了一系列 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];

正则循环与函数封装机制

正则表达式循环处理

代码示例如下:

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() {
//执行操作
} )(); 

这确实是最简单的技巧,但也是最实用的技巧。 奠定了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

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章