js怪招(摘录篇)

利用a标签自动解析URL

很多时候我们有从一个URL中提取域名,查询关键字,变量参数值等的需要,而万万没想到可以让浏览器方便地帮我们完成这一任务而不用我们写正则去抓取。方法就在JS代码里先创建一个a标签然后将需要解析的URL赋值给ahref属性,然后就得到了一切我们想要的了。

1 var a = document.createElement('a');
2  a.href = 'http://www.cnblogs.com/wayou/p/';
3  console.log(a.host);

利用这一原理,稍微扩展一下,就得到了一个更加健壮的解析URL各部分的通用方法了。下面代码来自James的博客

 1 // This function creates a new anchor element and uses location
 2 // properties (inherent) to get the desired URL data. Some String
 3 // operations are used (to normalize results across browsers).
 4  
 5 function parseURL(url) {
 6     var a =  document.createElement('a');
 7     a.href = url;
 8     return {
 9         source: url,
10         protocol: a.protocol.replace(':',''),
11         host: a.hostname,
12         port: a.port,
13         query: a.search,
14         params: (function(){
15             var ret = {},
16                 seg = a.search.replace(/^?/,'').split('&'),
17                 len = seg.length, i = 0, s;
18             for (;i<len;i++) {
19                 if (!seg[i]) { continue; }
20                 s = seg[i].split('=');
21                 ret[s[0]] = s[1];
22             }
23             return ret;
24         })(),
25         file: (a.pathname.match(//([^/?#]+)$/i) || [,''])[1],
26         hash: a.hash.replace('#',''),
27         path: a.pathname.replace(/^([^/])/,'/$1'),
28         relative: (a.href.match(/tps?://[^/]+(.+)/) || [,''])[1],
29         segments: a.pathname.replace(/^//,'').split('/')
30     };
31 }

生成随机字符串

利用Math.randomtoString生成随机字符串,来自前一阵子看到的一篇博文。    

1 function generateRandomAlphaNum(len) {
2     var rdmString = "";
3     for (; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
4     return rdmString.substr(0, len);
5 }

Math.floor的高效替代方案

利用好位操作符可以让我们获得效率上的提升,同时显得高端大气上档次。

|0~~是很好的一个例子,使用这两者可以完美替代Math.floor。在处理像素及动画位移等效果的时候会很有用,因为我们需要整数,而此方法比Math.floorparseInt效率都要高。性能比较见此

var foo = (12.4 / 4.13) | 0;//结果为3
var bar = ~~(12.4 / 4.13);//结果为3

注:整理有个重要的知识点:当 ~ 运算符充当非整型数据类型的操作数时,该值在运算执行之前被强制为 int 类型,该运算符的返回值为 int 类型。

顺便说句,!!将一个值方便快速转化为布尔值 !!window===true 。

禁止别人以iframe加载你的页面

下面的代码已经不言自明并,没什么好多说的。

1 if (window.location != window.parent.location) 
2   window.parent.location = window.location;
原文地址:https://www.cnblogs.com/wolm/p/3657788.html