javascript技巧

1.将arguments转化为数组
函数中的预定义变量arguments并非一个真正的数组,而是一个类似数组的对象。 
它具有length属性,但是没有slice, push, sort等函数,那么如何使arguments具有这些数组才有的函数呢? 
也就是说如何使arguments变成一个真正的数组呢?

function args(){

    return [].slice.call(arguments)

}

var m=args(2,5,8) // [2, 5, 8]

m.push(10)//可以使用数组方法

console.log(m)// [2, 5, 8,10]

 

2.

数组中的最大值

var arr = [2, 3, 45, 12, 8];

Math.max.apply(null, arr);// 45

 

3.修改arguments

function add() { 

       Array.prototype.push.call(arguments, 123);

 //因为arguments不是数组,是类数组,故需要调用数组方法

       return arguments; 

 } 

add(100); // [100,123]

4..If 中的假:null, undefined, NaN, 0, ‘’, false

 

5.encodeURI和encodeURIComponent  

window.encodeURI函数用来编码一个URL,但是不对这些编码:“:”, “/”, “;”, “?”. 
window.encodeURIComponent则会对上述字符进行编码。
我们通过一个例子来说明:

       'index.jsp?page='+encodeURI('/page/home.jsp');  // "index.jsp?page=/page/home.jsp"

       'index.jsp?page='+encodeURIComponent('/page/home.jsp');  // "index.jsp?page=%2Fpage%2Fhome.jsp"

因此,在对URL进行编码时我们经常会选择 encodeURIComponent。 

posted @ 2014-07-25 13:47  hlp鹏  阅读(106)  评论(0编辑  收藏  举报