JavaScript 实用技巧与高效编程方法汇总

作者:闭包旅人

时间:2026-10-29

浏览:270

本文汇总了 JavaScript 开发中的实用技巧与高效编程方法。内容涵盖变量类型转换、数组去重与插入、最大值查找及随机数生成等常见场景。通过利用原生方法和位运算,可显著简化代码逻辑并提升执行效率,同时包含事件委派、循环控制及浏览器检测等进阶技巧,帮助开发者写出更简洁优雅的代码。

文章目录

变量类型转换与数值处理

变量类型转换


var myVar  = "3.14159",
str   = ""+ myVar,// to string
int   = ~~myVar, // to integer
float  = 1*myVar, // to float
bool  = !!myVar, /* to boolean - any string with length
and any number except 0 are true */
array  = [myVar]; // to array


 

然而,将变量转换为日期(new Date(myVar))或正则表达式(new RegExp(myVar))时,必须使用构造函数。在创建正则表达式时,建议使用 /pattern/flags 这种简写形式。

利用位运算实现取整并同时转换为数值型。


//字符型变量参与运算时,JS会自动将其转换为数值型(如果无法转化,变为NaN)
    '10.567890' | 0
    //结果: 10
    //JS里面的所有数值型都是双精度浮点数,因此,JS在进行位运算时,会首先将这些数字运算数转换为整数,然后再执行运算
    //| 是二进制或, x|0 永远等于x;^为异或,同0异1,所以 x^0 还是永远等于x;至于~是按位取反,搞了两次以后值当然是一样的
    '10.567890' ^ 0    
    //结果: 10
    - 2.23456789 | 0
    //结果: -2
    ~~-2.23456789
    //结果: -2

将日期对象转换为数值型时间戳。


    //JS本身时间的内部表示形式就是Unix时间戳,以毫秒为单位记录着当前距离1970年1月1日0点的时间单位
    var d = +new Date(); //1295698416792

 

数组操作技巧

将类数组对象转换为真正的数组。


var arr =[].slice.call(arguments)


 

以下示例展示了更为巧妙的用法。


function test() {
  var res = ['item1', 'item2']
  res = res.concat(Array.prototype.slice.call(arguments)) //方法1
  Array.prototype.push.apply(res, arguments)       //方法2
}

实现不同进制之间的数值转换。


(int).toString(16); // converts int to hex, eg 12 => "C"
(int).toString(8); // converts int to octal, eg. 12 => "14"
parseInt(string,16) // converts hex to int, eg. "FF" => 255
parseInt(string,8) // converts octal to int, eg. "20" => 16

将另一个数组插入到指定数组的特定位置。


var a = [1,2,3,7,8,9];
var b = [4,5,6];
var insertIndex = 3;
a.splice.apply(a, Array.prototype.concat(insertIndex, 0, b));

从数组中删除指定元素。


var a = [1,2,3,4,5];
a.splice(3,1);      //a = [1,2,3,5]

有人可能会疑惑为何使用 splice 而非 delete。这是因为 delete 操作会在数组中留下空洞,且后续元素的索引并不会自动递减。

浏览器检测与兼容性处理

判断当前浏览器是否为 Internet Explorer (IE)。


var ie = /*@cc_on !@*/false;

仅用一行简单代码即可判断是否为 IE,效果显著。

实际上还有更多巧妙的检测方法,详见下文。


// 貌似是最短的,利用IE不支持标准的ECMAscript中数组末逗号忽略的机制
var ie = !-[1,];
// 利用了IE的条件注释
var ie = /*@cc_on!@*/false;
// 还是条件注释
var ie//@cc_on=1;
// IE不支持垂直制表符
var ie = '\v'=='v';
// 原理同上
var ie = !+"\v1";

掌握这些技巧后,往往会对之前的写法感到不足。

利用原生方法优化代码

在开发中,应尽可能利用语言提供的原生方法。

若要查找一组数字中的最大值,常规做法是编写循环,例如:


var numbers = [3,342,23,22,124];
var max = 0;
for(var i=0;i<numbers.length;i++){
 if(numbers[i] > max){
  max = numbers[i];
 }
}
alert(max);

实际上,利用原生方法可以实现更简洁的代码。


var numbers = [3,342,23,22,124];
numbers.sort(function(a,b){return b - a});
alert(numbers[0]);

当然,最简洁的写法如下:


Math.max(12,123,3,2,433,4); // returns 433

此外,还可以采用以下方式实现。


Math.max.apply(Math, [12, 123, 3, 2, 433, 4]) //取最大值
Math.min.apply(Math, [12, 123, 3, 2, 433, 4]) //取最小值

随机数生成与变量交换

生成随机数的方法。


    Math.random().toString(16).substring(2);// toString() 函数的参数为基底,范围为2~36。
    Math.random().toString(36).substring(2);

无需借助第三方变量即可交换两个变量的值。


a=[b, b=a][0];

事件委派与 DOM 操作

利用事件委派机制优化事件处理。

以下是一个简单的 HTML 代码示例:


<h2>Great Web resources</h2>
<ul id="resources">
 <li><a href="http://opera.com/wsc">Opera Web Standards Curriculum</a></li>
 <li><a href="http://sitepoint.com">Sitepoint</a></li>
 <li><a href="http://alistapart.com">A List Apart</a></li>
 <li><a href="http://yuiblog.com">YUI Blog</a></li>
 <li><a href="http://blameitonthevoices.com">Blame it on the voices</a></li>
 <li><a href="http://oddlyspecific.com">Oddly specific</a></li>
</ul>


对应的 JavaScript 代码如下:


// Classic event handling example
(function(){
 var resources = document.getElementById('resources');
 var links = resources.getElementsByTagName('a');
 var all = links.length;
 for(var i=0;i<all;i++){
  // Attach a listener to each link
  links[i].addEventListener('click',handler,false);
 };
 function handler(e){
  var x = e.target; // Get the link that was clicked
  alert(x);
  e.preventDefault();
 };
})();


利用事件委派可以写出更加优雅且高效的代码。


(function(){
 var resources = document.getElementById('resources');
 resources.addEventListener('click',handler,false);
 function handler(e){
  var x = e.target; // get the link tha
  if(x.nodeName.toLowerCase() === 'a'){
   alert('Event delegation:' + x);
   e.preventDefault();
  }
 };
})();

环境检测与属性判断

检测具体的 IE 浏览器版本。


var _IE = (function(){
  var v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i');
  while (
    div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
    all[0]
  );
  return v > 4 ? v : false ;
}());

检测当前环境支持的 JavaScript 语言版本。

了解你的浏览器支持哪个版本的 JavaScript 标准。


var JS_ver = [];
(Number.prototype.toFixed)?JS_ver.push("1.5"):false;
([].indexOf && [].forEach)?JS_ver.push("1.6"):false;
((function(){try {[a,b] = [0,1];return true;}catch(ex) {return false;}})())?JS_ver.push("1.7"):false;
([].reduce && [].reduceRight && JSON)?JS_ver.push("1.8"):false;
("".trimLeft)?JS_ver.push("1.8.1"):false;
JS_ver.supports = function()
{
  if (arguments[0])
    return (!!~this.join().indexOf(arguments[0] +",") +",");
  else
    return (this[this.length-1]);
}
alert("Latest Javascript version supported: "+ JS_ver.supports());
alert("Support for version 1.7 : "+ JS_ver.supports("1.7"));

判断对象属性是否存在。


// BAD: This will cause an error in code when foo is undefined
if (foo) {
  doSomething();
}
// GOOD: This doesn't cause any errors. However, even when
// foo is set to NULL or false, the condition validates as true
if (typeof foo != "undefined") {
  doSomething();
}
// BETTER: This doesn't cause any errors and in addition
// values NULL or false won't validate as true
if (window.foo) {
  doSomething();
}

在某些情况下,面对更深层的数据结构,需要采用更合适的检查方式。


// UGLY: we have to proof existence of every
// object before we can be sure property actually exists
if (window.oFoo && oFoo.oBar && oFoo.oBar.baz) {
  doSomething();
}

实际上,检测属性是否存在的最优方法如下:


if("opera" in window){
  console.log("OPERA");
}else{
  console.log("NOT OPERA");
}

检测一个对象是否为数组类型。


var obj=[];
Object.prototype.toString.call(obj)=="[object Array]";

高级函数应用与循环控制

向函数传递对象参数的技巧。


function doSomething() {
  // Leaves the function if nothing is passed
  if (!arguments[0]) {
  return false;
  }
  var oArgs  = arguments[0]
  arg0  = oArgs.arg0 || "",
  arg1  = oArgs.arg1 || "",
  arg2  = oArgs.arg2 || 0,
  arg3  = oArgs.arg3 || [],
  arg4  = oArgs.arg4 || false;
}
doSomething({
  arg1  : "foo",
  arg2  : 5,
  arg4  : false
});

为 replace 方法传递一个函数作为参数。


var sFlop  = "Flop: [Ah] [Ks] [7c]";
var aValues = {"A":"Ace","K":"King",7:"Seven"};
var aSuits = {"h":"Hearts","s":"Spades",
"d":"Diamonds","c":"Clubs"};
sFlop  = sFlop.replace(/\[\w+\]/gi, function(match) {
  match  = match.replace(match[2], aSuits[match[2]]);
  match  = match.replace(match[1], aValues[match[1]] +" of ");
  return match;
});
// string sFlop now contains:
// "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"

在循环中使用标签(label)进行控制。

当循环中嵌套循环时,若需退出某一层循环,过去常使用标志变量判断,现在有更优的方法。


outerloop:
for (var iI=0;iI<5;iI++) {
  if (somethingIsTrue()) {
  // Breaks the outer loop iteration
  break outerloop;
  }
  innerloop:
  for (var iA=0;iA<5;iA++) {
    if (somethingElseIsTrue()) {
    // Breaks the inner loop iteration
    break innerloop;
  }
  }
}

数组去重与字符串处理

对数组进行去重处理。


/*
*@desc:对数组进行去重操作,返回一个没有重复元素的新数组
*/
function unique(target) {
  var result = [];
  loop: for (var i = 0, n = target.length; i < n; i++) {
    for (var x = i + 1; x < n; x++) {
      if (target[x] === target[i]) {
        continue loop;
      }
    }
    result.push(target[i]);
  }
  return result;
}

或者采用如下方式实现。



Array.prototype.distinct = function () {
  var newArr = [],obj = {};
  for(var i=0, len = this.length; i < len; i++){
    if(!obj[typeof(this[i]) + this[i]]){
      newArr.push(this[i]);
      obj[typeof(this[i]) + this[i]] = 'new';
    }
  }
  return newArr;
}

实际上,最优的去重方法如下所示。



Array.prototype.distinct = function () { 
  var sameObj = function(a, b){ 
    var tag = true; 
    if(!a || !b) return false; 
    for(var x in a){ 
      if(!b[x]) return false; 
      if(typeof(a[x]) === 'object'){ 
        tag = sameObj(a[x],b[x]); 
      } else { 
        if(a[x]!==b[x]) 
        return false; 
      } 
    } 
    return tag; 
  } 
  var newArr = [], obj = {}; 
  for(var i = 0, len = this.length; i < len; i++){ 
    if(!sameObj(obj[typeof(this[i]) + this[i]], this[i])){ 
    newArr.push(this[i]); 
    obj[typeof(this[i]) + this[i]] = this[i]; 
    } 
  } 
  return newArr; 
}

使用范例(参考自评论):


var arr=[{name:"tom",age:12},{name:"lily",age:22},{name:"lilei",age:12}];
var newArr=arr.distinct(function(ele){
 return ele.age;
});

查找字符串中出现频率最高的字符及其出现次数。


var i, len, maxobj='', maxnum=0, obj={};
var arr = "sdjksfssscfssdd";
for(i = 0, len = arr.length; i < len; i++){
  obj[arr[i]] ? obj[arr[i]]++ : obj[arr[i]] = 1;
  if(maxnum < obj[arr[i]]){
    maxnum = obj[arr[i]];
    maxobj = arr[i];
  }
}
alert(maxobj + "在数组中出现了" + maxnum + "次");


此外还有更多技巧,以上仅是闲暇时总结的部分内容。

实用工具推荐

电子包浆

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

使用 ›
图片压缩

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

使用 ›
相关文章