Javascript学习总结-技巧、实用函数、简介方法、编程细

整理JavaScript方面的一些技巧,比较实用的函数,常见功能实现方法,仅作参考


变量转换
[js]  view plain copy
  1. //edit http://www.lai18.com   
  2. var myVar  = "3.14159",  
  3. str   = ""+ myVar,// to string  
  4. int   = ~~myVar, // to integer  
  5. float  = 1*myVar, // to float  
  6. bool  = !!myVar, /* to boolean - any string with length 
  7. and any number except 0 are true */  
  8. array  = [myVar]; // to array  
但是转换日期(new Date(myVar))和正则表达式(new RegExp(myVar))必须使用构造函数,创建正则表达式的时候要使用/pattern/flags这样的简化形式。 

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

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

类数组对象转数组
[js]  view plain copy
  1. var arr =[].slice.call(arguments)  

下面的实例用的更绝
[js]  view plain copy
  1. function test() {  
  2.   var res = ['item1''item2']  
  3.   res = res.concat(Array.prototype.slice.call(arguments)) //方法1  
  4.   Array.prototype.push.apply(res, arguments)       //方法2  
  5. }  

进制之间的转换
[js]  view plain copy
  1. (int).toString(16); // converts int to hex, eg 12 => "C"  
  2. (int).toString(8); // converts int to octal, eg. 12 => "14"  
  3. parseInt(string,16) // converts hex to int, eg. "FF" => 255  
  4. parseInt(string,8) // converts octal to int, eg. "20" => 16  


将一个数组插入另一个数组指定的位置
[js]  view plain copy
  1. var a = [1,2,3,7,8,9];  
  2. var b = [4,5,6];  
  3. var insertIndex = 3;  
  4. a.splice.apply(a, Array.prototype.concat(insertIndex, 0, b));  

删除数组元素
[js]  view plain copy
  1. var a = [1,2,3,4,5];  
  2. a.splice(3,1);      //a = [1,2,3,5]  

大家也许会想为什么要用splice而不用delete,因为用delete将会在数组里留下一个空洞,而且后面的下标也并没有递减。
判断是否为IE
[js]  view plain copy
  1. var ie = /*@cc_on !@*/false;  
这样一句简单的话就可以判断是否为ie,太。。。
其实还有更多妙的方法,请看下面
[js]  view plain copy
  1. //edit http://www.lai18.com   
  2. // 貌似是最短的,利用IE不支持标准的ECMAscript中数组末逗号忽略的机制  
  3. var ie = !-[1,];  
  4. // 利用了IE的条件注释  
  5. var ie = /*@cc_on!@*/false;  
  6. // 还是条件注释  
  7. var ie//@cc_on=1;  
  8. // IE不支持垂直制表符  
  9. var ie = '\v'=='v';  
  10. // 原理同上  
  11. var ie = !+"\v1";  

学到这个瞬间觉得自己弱爆了。
尽量利用原生方法

要找一组数字中的最大数,我们可能会写一个循环,例如:
[js]  view plain copy
  1. var numbers = [3,342,23,22,124];  
  2. var max = 0;  
  3. for(var i=0;i<numbers.length;i++){  
  4.  if(numbers[i] > max){  
  5.   max = numbers[i];  
  6.  }  
  7. }  
  8. alert(max);  

其实利用原生的方法,可以更简单实现
[js]  view plain copy
  1. var numbers = [3,342,23,22,124];  
  2. numbers.sort(function(a,b){return b - a});  
  3. alert(numbers[0]);  

当然最简洁的方法便是:
[js]  view plain copy
  1. Math.max(12,123,3,2,433,4); // returns 433  
当前也可以这样
[xhtml]  view plain copy
  1. Math.max.apply(Math, [12, 123, 3, 2, 433, 4]) //取最大值  
  2. Math.min.apply(Math, [12, 123, 3, 2, 433, 4]) //取最小值  
生成随机数
[js]  view plain copy
  1. Math.random().toString(16).substring(2);// toString() 函数的参数为基底,范围为2~36。  
  2.     Math.random().toString(36).substring(2);  
不用第三方变量交换两个变量的值
[js]  view plain copy
  1. a=[b, b=a][0];  

事件委派

举个简单的例子:html代码如下
[js]  view plain copy
  1. <h2>Great Web resources</h2>  
  2. <ul id="resources">  
  3.  <li><a href="http://opera.com/wsc">Opera Web Standards Curriculum</a></li>  
  4.  <li><a href="http://sitepoint.com">Sitepoint</a></li>  
  5.  <li><a href="http://alistapart.com">A List Apart</a></li>  
  6.  <li><a href="http://yuiblog.com">YUI Blog</a></li>  
  7.  <li><a href="http://blameitonthevoices.com">Blame it on the voices</a></li>  
  8.  <li><a href="http://oddlyspecific.com">Oddly specific</a></li>  
  9. </ul>  

js代码如下:
[js]  view plain copy
  1. // Classic event handling example  
  2. (function(){  
  3.  var resources = document.getElementById('resources');  
  4.  var links = resources.getElementsByTagName('a');  
  5.  var all = links.length;  
  6.  for(var i=0;i<all;i++){  
  7.   // Attach a listener to each link  
  8.   links[i].addEventListener('click',handler,false);  
  9.  };  
  10.  function handler(e){  
  11.   var x = e.target; // Get the link that was clicked  
  12.   alert(x);  
  13.   e.preventDefault();  
  14.  };  
  15. })();  

利用事件委派可以写出更加优雅的:
[js]  view plain copy
  1. (function(){  
  2.  var resources = document.getElementById('resources');  
  3.  resources.addEventListener('click',handler,false);  
  4.  function handler(e){  
  5.   var x = e.target; // get the link tha  
  6.   if(x.nodeName.toLowerCase() === 'a'){  
  7.    alert('Event delegation:' + x);  
  8.    e.preventDefault();  
  9.   }  
  10.  };  
  11. })();  

检测ie版本
[js]  view plain copy
  1. var _IE = (function(){  
  2.   var v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i');  
  3.   while (  
  4.     div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',  
  5.     all[0]  
  6.   );  
  7.   return v > 4 ? v : false ;  
  8. }());  

javaScript版本检测
你知道你的浏览器支持哪一个版本的Javascript吗?
[js]  view plain copy
  1. var JS_ver = [];  
  2. (Number.prototype.toFixed)?JS_ver.push("1.5"):false;  
  3. ([].indexOf && [].forEach)?JS_ver.push("1.6"):false;  
  4. ((function(){try {[a,b] = [0,1];return true;}catch(ex) {return false;}})())?JS_ver.push("1.7"):false;  
  5. ([].reduce && [].reduceRight && JSON)?JS_ver.push("1.8"):false;  
  6. ("".trimLeft)?JS_ver.push("1.8.1"):false;  
  7. JS_ver.supports = function()  
  8. {  
  9.   if (arguments[0])  
  10.     return (!!~this.join().indexOf(arguments[0] +",") +",");  
  11.   else  
  12.     return (this[this.length-1]);  
  13. }  
  14. alert("Latest Javascript version supported: "+ JS_ver.supports());  
  15. alert("Support for version 1.7 : "+ JS_ver.supports("1.7"));  
判断属性是否存在
[js]  view plain copy
  1. // BAD: This will cause an error in code when foo is undefined  
  2. if (foo) {  
  3.   doSomething();  
  4. }  
  5. // GOOD: This doesn't cause any errors. However, even when  
  6. // foo is set to NULL or false, the condition validates as true  
  7. if (typeof foo != "undefined") {  
  8.   doSomething();  
  9. }  
  10. // BETTER: This doesn't cause any errors and in addition  
  11. // values NULL or false won't validate as true  
  12. if (window.foo) {  
  13.   doSomething();  
  14. }  
有的情况下,我们有更深的结构和需要更合适的检查的时候
[js]  view plain copy
  1. // UGLY: we have to proof existence of every  
  2. // object before we can be sure property actually exists  
  3. if (window.oFoo && oFoo.oBar && oFoo.oBar.baz) {  
  4.   doSomething();  
  5. }  
其实最好的检测一个属性是否存在的方法为:
[js]  view plain copy
  1. if("opera" in window){  
  2.   console.log("OPERA");  
  3. }else{  
  4.   console.log("NOT OPERA");  
  5. }  

检测对象是否为数组
[js]  view plain copy
  1. var obj=[];  
  2. Object.prototype.toString.call(obj)=="[object Array]";  

给函数传递对象
[js]  view plain copy
  1. function doSomething() {  
  2.   // Leaves the function if nothing is passed  
  3.   if (!arguments[0]) {  
  4.   return false;  
  5.   }  
  6.   var oArgs  = arguments[0]  
  7.   arg0  = oArgs.arg0 || "",  
  8.   arg1  = oArgs.arg1 || "",  
  9.   arg2  = oArgs.arg2 || 0,  
  10.   arg3  = oArgs.arg3 || [],  
  11.   arg4  = oArgs.arg4 || false;  
  12. }  
  13. doSomething({  
  14.   arg1  : "foo",  
  15.   arg2  : 5,  
  16.   arg4  : false  
  17. });  

为replace方法传递一个函数
[js]  view plain copy
  1. var sFlop  = "Flop: [Ah] [Ks] [7c]";  
  2. var aValues = {"A":"Ace","K":"King",7:"Seven"};  
  3. var aSuits = {"h":"Hearts","s":"Spades",  
  4. "d":"Diamonds","c":"Clubs"};  
  5. sFlop  = sFlop.replace(/
    \w+
    /gi, function(match) {  
  6.   match  = match.replace(match[2], aSuits[match[2]]);  
  7.   match  = match.replace(match[1], aValues[match[1]] +" of ");  
  8.   return match;  
  9. });  
  10. // string sFlop now contains:  
  11. // "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"  
循环中使用标签
有时候循环当中嵌套循环,你可能想要退出某一层循环,之前总是用一个标志变量来判断,现在才知道有更好的方法
[js]  view plain copy
  1. outerloop:  
  2. for (var iI=0;iI<5;iI++) {  
  3.   if (somethingIsTrue()) {  
  4.   // Breaks the outer loop iteration  
  5.   break outerloop;  
  6.   }  
  7.   innerloop:  
  8.   for (var iA=0;iA<5;iA++) {  
  9.     if (somethingElseIsTrue()) {  
  10.     // Breaks the inner loop iteration  
  11.     break innerloop;  
  12.   }  
  13.   }  
  14. }  
对数组进行去重
[js]  view plain copy
  1. /* 
  2. *@desc:对数组进行去重操作,返回一个没有重复元素的新数组 
  3. */  
  4. function unique(target) {  
  5.   var result = [];  
  6.   loop: for (var i = 0, n = target.length; i < n; i++) {  
  7.     for (var x = i + 1; x < n; x++) {  
  8.       if (target[x] === target[i]) {  
  9.         continue loop;  
  10.       }  
  11.     }  
  12.     result.push(target[i]);  
  13.   }  
  14.   return result;  
  15. }  

或者如下:
[js]  view plain copy
  1. Array.prototype.distinct = function () {  
  2.   var newArr = [],obj = {};  
  3.   for(var i=0, len = this.length; i < len; i++){  
  4.     if(!obj[typeof(this[i]) + this[i]]){  
  5.       newArr.push(this[i]);  
  6.       obj[typeof(this[i]) + this[i]] = 'new';  
  7.     }  
  8.   }  
  9.   return newArr;  
  10. }  

其实最优的方法是这样的
[js]  view plain copy
  1. Array.prototype.distinct = function () {   
  2.   var sameObj = function(a, b){   
  3.     var tag = true;   
  4.     if(!a || !b) return false;   
  5.     for(var x in a){   
  6.       if(!b[x]) return false;   
  7.       if(typeof(a[x]) === 'object'){   
  8.         tag = sameObj(a[x],b[x]);   
  9.       } else {   
  10.         if(a[x]!==b[x])   
  11.         return false;   
  12.       }   
  13.     }   
  14.     return tag;   
  15.   }   
  16.   var newArr = [], obj = {};   
  17.   for(var i = 0, len = this.length; i < len; i++){   
  18.     if(!sameObj(obj[typeof(this[i]) + this[i]], this[i])){   
  19.     newArr.push(this[i]);   
  20.     obj[typeof(this[i]) + this[i]] = this[i];   
  21.     }   
  22.   }   
  23.   return newArr;   
  24. }  

使用范例(借用评论):
[js]  view plain copy
  1. var arr=[{name:"tom",age:12},{name:"lily",age:22},{name:"lilei",age:12}];  
  2. var newArr=arr.distinct(function(ele){  
  3.  return ele.age;  
  4. });  

查找字符串中出现最多的字符及个数
[js]  view plain copy
  1. var i, len, maxobj='', maxnum=0, obj={};  
  2. var arr = "sdjksfssscfssdd";  
  3. for(i = 0, len = arr.length; i < len; i++){  
  4.   obj[arr[i]] ? obj[arr[i]]++ : obj[arr[i]] = 1;  
  5.   if(maxnum < obj[arr[i]]){  
  6.     maxnum = obj[arr[i]];  
  7.     maxobj = arr[i];  
  8.   }  
  9. }  
  10. alert(maxobj + "在数组中出现了" + maxnum + "次");  

其实还有很多,这些只是我闲来无事总结的一些罢了。 

转载自http://blog.csdn.net/hello_katty/article/details/46452999

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值