个人总结的一些JavaScript技巧、实用函数、简洁方(2)

(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]"

循环中使用标签

有时候循环当中嵌套循环,你可能想要退出某一层循环,之前总是用一个标志变量来判断,现在才知道有更好的方法

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; });

查找字符串中出现最多的字符及个数

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgdssf.html