JavaScript小技巧

来源:互联网 发布:网络福禄克怎么测试 编辑:程序博客网 时间:2024/06/06 20:24
1、变量转换
[js] view plaincopy
  1. var myVar  = "3.14159",  
  2. str   = ""+ myVar,// to string  
  3. int   = ~~myVar, // to integer  
  4. float  = 1*myVar, // to float  
  5. bool  = !!myVar, /* to boolean - any string with length 
  6. and any number except 0 are true */  
  7. array  = [myVar]; // to array  
但是转换日期(new Date(myVar))和正则表达式(new RegExp(myVar))必须使用构造函数,创建正则表达式的时候要使用/pattern/flags这样的简化形式。 



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



3、日期转换

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

想得到format后的时间?现在不用再get年月日时分秒了,三步搞定

[js] view plaincopy
  1. var temp = new Date();  
  2. var regex = /\//g;  
  3. (temp.toLocaleDateString() + ' ' + temp.toLocaleTimeString().slice(2)).replace(regex,'-');  

  4. // "2015-5-7 9:04:10"  
想将format后的时间转换为时间对象?直接用Date的构造函数
[js] view plaincopy
  1. new Date("2015-5-7 9:04:10");  
  2. // Thu May 07 2015 09:04:10 GMT+0800 (CST)  
想将一个标准的时间对象转换为unix时间戳?valueOf搞定之
[js] view plaincopy
  1. (new Date).valueOf();  
  2. // 1431004132641  


4、类数组对象转数组
[js] view plaincopy
  1. var arr =[].slice.call(arguments)  
下面的实例用的更绝
[js] view plaincopy
  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. }  



5、进制之间的转换
[js] view plaincopy
  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  



6、将一个数组插入另一个数组指定的位置
[js] view plaincopy
  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));  


7、删除数组元素
[js] view plaincopy
  1. var a = [1,2,3,4,5];  
  2. a.splice(3,1);      //a = [1,2,3,5]  
大家也许会想为什么要用splice而不用delete,因为用delete将会在数组里留下一个空洞,而且后面的下标也并没有递减。




8、判断是否为IE
[js] view plaincopy
  1. var ie = /*@cc_on !@*/false;  
这样一句简单的话就可以判断是否为ie,太。。。
其实还有更多妙的方法,请看下面
[js] view plaincopy
  1. // 貌似是最短的,利用IE不支持标准的ECMAscript中数组末逗号忽略的机制  
  2. var ie = !-[1,];  
  3. // 利用了IE的条件注释  
  4. var ie = /*@cc_on!@*/false;  
  5. // 还是条件注释  
  6. var ie//@cc_on=1;  
  7. // IE不支持垂直制表符  
  8. var ie = '\v'=='v';  
  9. // 原理同上  
  10. var ie = !+"\v1";  
学到这个瞬间觉得自己弱爆了。



9、尽量利用原生方法

要找一组数字中的最大数,我们可能会写一个循环,例如:
[js] view plaincopy
  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 plaincopy
  1. var numbers = [3,342,23,22,124];  
  2. numbers.sort(function(a,b){return b - a});  
  3. alert(numbers[0]);  
当然最简洁的方法便是:
[js] view plaincopy
  1. Math.max(12,123,3,2,433,4); // returns 433  
当前也可以这样
[xhtml] view plaincopy
  1. Math.max.apply(Math, [12, 123, 3, 2, 433, 4]) //取最大值  
  2. Math.min.apply(Math, [12, 123, 3, 2, 433, 4]) //取最小值  


10、生成随机数
[js] view plaincopy
  1. Math.random().toString(16).substring(2);// toString() 函数的参数为基底,范围为2~36。  
  2.     Math.random().toString(36).substring(2);  


11、不用第三方变量交换两个变量的值
[js] view plaincopy
  1. a=[b, b=a][0];  


12、事件委派

举个简单的例子:html代码如下
[js] view plaincopy
  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 plaincopy
  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 plaincopy
  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. })();  


13、检测ie版本
[js] view plaincopy
  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. }());  


14、javaScript版本检测


你知道你的浏览器支持哪一个版本的Javascript吗?
[js] view plaincopy
  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"));  


15、判断属性是否存在
[js] view plaincopy
  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 plaincopy
  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 plaincopy
  1. if("opera" in window){  
  2.   console.log("OPERA");  
  3. }else{  
  4.   console.log("NOT OPERA");  
  5. }  


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


17、给函数传递对象
[js] view plaincopy
  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. });  


18、为replace方法传递一个函数
[js] view plaincopy
  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]"  


19、循环中使用标签

有时候循环当中嵌套循环,你可能想要退出某一层循环,之前总是用一个标志变量来判断,现在才知道有更好的方法
[js] view plaincopy
  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. }  


20、对数组进行去重
[js] view plaincopy
  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 plaincopy
  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 plaincopy
  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 plaincopy
  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. });  


21、查找字符串中出现最多的字符及个数
[js] view plaincopy
  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 + "次");  



22、& (按位与) 

判断一个数是否为2的n次幂,可以将其与自身减一相与

[js] view plaincopy
  1. var number = 4  
  2. (number & number -1) === 0 // true  


23、^ (按位异或)
不同第三个变量,就可以交换两个变量的值

[js] view plaincopy
  1. var a = 4,b = 3  
  2. a = a ^ b //  7  
  3. b = a ^ b //  4  
  4. a = b ^ a //  3  



24、一元加可以快速将字符串的数字转换为数学数字,即

[js] view plaincopy
  1. var number = "23"   
  2. typeof number // string  
  3. typeof +number // number  



25、转义URI

需要将url当做参数在路由中传递,现在转义之

[js] view plaincopy
  1. var url = encodeURIComponent('http://segmentfault.com/questions/newest')  
  2.   
  3. // "http%3A%2F%2Fsegmentfault.com%2Fquestions%2Fnewest"  
再反转义
[js] view plaincopy
  1. decodeURIComponent(url)  
  2. // "http://segmentfault.com/questions/newest"  



26、Number
希望保留小数点后的几位小数,不用再做字符串截取了,toFixed拿走

[js] view plaincopy
  1. number.toFixed()   // "12346"  
  2. number.toFixed(3)  // "12345.679"  
  3. number.toFixed(6)  // "12345.678900"  
参数范围为0~20,不写默认0



27、toExponential()

toExponential() 方法可把对象的值转换成指数计数法。

[js] view plaincopy
  1. var num = 10000.1234;  
  2. console.log(num.toExponential());    //1.00001234e+4  
  3. console.log(num.toExponential(2));   //1.00e+4  
  4. console.log(num.toExponential(10));  //1.0000123400e+4  



28、toPrecision()

toPrecision() 方法可将数值格式化为一个十进制数形式的字符串

参数num是可选的。用于控制数字的精度。该参数是 1 ~ 21 之间(且包括 1 和 21)的值。如果省略了该参数,则调用方法 toString(),而不是把数字转换成十进制的值。

[js] view plaincopy
  1. var num = 10000.1234;  
  2. console.log(num.toPrecision());    //10000.1234  
  3. console.log(num.toPrecision(2));   //1.0e+4  
  4. console.log(num.toPrecision(10));  //10000.12340  





0 0
原创粉丝点击