ECMASCRIPT5新特性(转载)

浏览器对照表http://kangax.github.com/es5-compat-table/

 

Function 1: Object.create

这是一个很重要的改动,现在我们终于可以得到一个原型链干净的对象了。以前要创建一个类

 

Js代码  收藏代码
  1. function Cat(name) {  
  2.     this.name   = name;                                                                                   
  3.     this.paws   = 4;  
  4.     this.hungry = false;  
  5.     this.eaten  = [];  
  6. }  
  7. Cat.prototype = {  
  8.     constructor : Cat,  
  9.     play        : function () { this.hungry = truereturn 'playing!'; },  
  10.       feed        : function (food) { this.eaten.push(food); this.hungry = false; },  
  11.     speak       : function () { return 'Meow'; }  
  12. };  

 必须要分两步走,但是现在可以不必了

 

Js代码  收藏代码
  1. var Dog = {  
  2.     name   : 'dog',  
  3.     paws   : 4,  
  4.     hungry : false,  
  5.     eaten  : null,  
  6.     play   : function () { this.hungry = truereturn 'playing!'; },  
  7.     speak  : function () { return 'Woof!'; }  
  8. };  
  9. var dog = Object.create(Dog);  

 Object.create他还有第2个参数,是一个properties descriptor object 关于这方面的详细解释,请看第2点。


另外:如果浏览器不支持Object.create,可以用这种方法代替

 

Js代码  收藏代码
  1. if (typeof Object.create !== 'function') {  
  2.     Object.create = function (o) {  
  3.         function F() {}  
  4.         F.prototype = o;  
  5.         return new F();  
  6.     };  
  7. }  

 Browser Support

   ○ Firefox 4

   ○ Internet Explorer 9

   ○ Safari 5

   ○ Chrome 5+

 

 

Function 2: Object.defineProperty

 

如果你想为一个对象定义属性,那么就必须my_dog.age = 2; 用这种方法。但是在ECMAScript5中,提供了更好的包装方法Object.defineProperty

Parameters:

1.对象引用

2.属性名

3.修饰对象

修饰对象中的定义如下:

 value: use this to set the value of a property. Defaults to undefined.

 writable: use this boolean to define whether this is a read-only variable. If it’s writable, it’s true. Defaults to false.

 configurable: use this boolean to define whether the type (value vs. method) of this property can be changed, or whether the property can be deleted. If it’s configurable, it’s true. Defaults to false.

 enumerable: use this boolean to define whether this property is included when the properties of the object are enumerated (a for-in loop or the keys method). Defaults to false.

 get: use this to define a custom getter method. Defaults to undefined.

 set: use this to define a custom setter method. Defaults to undefined.

 

Sample:

 

Js代码  收藏代码
  1. var Dog = {  
  2.     name   : 'dog',  
  3.     paws   : 4  
  4. };  
  5. var dog = Object.create(Dog);  
  6.   
  7. Object.defineProperty(dog, 'age', {  
  8.     set : function (age) { this.humanYears = age * 7; },  
  9.     get : function () { return this.humanYears / 7; },  
  10.     enumerable : true  
  11. });  
  12.   
  13. dog.age = 2;  
  14. dog.humanYears; // 14  

 以上代码让agehumanYears保存了同步,如果你不想对外界暴露humanYears,可以这样使用闭包:

 

Js代码  收藏代码
  1. Object.defineProperty(dog, 'age', (function () {  
  2.     var humanYears;  
  3.   
  4.     return {  
  5.         set : function (age) { humanYears = age * 7; },  
  6.         get : function () { return humanYears / 7; },  
  7.         enumerable : true  
  8.     };  
  9.   
  10. }()));  

 当然,也可以用在Object.create方法上面

 

Js代码  收藏代码
  1. var yourDog = Object.create(Dog, {  
  2.     age : {  
  3.         get : function () { /* . . . */ },  
  4.         set : function () { /* . . . */ },  
  5.         enumerable: true  
  6.     },  
  7.     gender : {  
  8.         value : 'female'  
  9.     }  
  10. });  

 Browser Support

   ○ Firefox 4

   ○ Internet Explorer 9

   ○ Safari 5

   ○ Chrome 5+

 

 

Function 3: Object.defineProperties

当然,如果你想像Object.create方法那样一口气给对象加入很多属性的话,你可以用Object.defineProperties方法

 

Js代码  收藏代码
  1. Object.defineProperties(dog, {  
  2.     age : {  
  3.         get : function () { /* . . . */ },  
  4.         set : function () { /* . . . */ },  
  5.         enumerable: true  
  6.     },  
  7.     gender : {  
  8.         value : 'female'  
  9.     }  
  10. });  

 注意区别 Object.createObject.defineProperties第一个参数的不同,Object.createprototype,而Object.defineProperties是对象


Browser Support

   ○ Firefox 4

   ○ Internet Explorer 9

   ○ Safari 5

   ○ Chrome 5+

Function 4: Object.getOwnPropertyDescriptor

用途:得到一个属性的定义

 

 

Js代码  收藏代码
  1. var person = { name : 'Joe' };  
  2. Object.getOwnPropertyDescriptor(person, 'name'); // { configurable : true,enumerable : true, value : 'Joe&', writable : true }  

 但是这个函数只能适用于函数自身的对象,并不能取得原型链上的属性

Browser Support

○ Firefox 4

○ Internet Explorer 9

○ Safari 5

○ Chrome 5+

 

Function 5: Object.keys

用途:取得所有的属性名

 

 

Js代码  收藏代码
  1. var horse = { name : 'Ed', age : 4, job : 'jumping', owner : 'Jim' };  
  2. var horseKeys = Object.keys(horse); // ['name', 'age', 'job', 'owner'];  

 

 

Browser Support

○ Firefox 4

○ Internet Explorer 9

○ Safari 5

○ Chrome 5+

 

 

Function 6: Object.getOwnPropertyNames

此函数功能基本和第5点相同,但是她可以取得所有的属性名,即使那个属性是不可枚取的(属性的enumerable =false,详细请参照第2点)

Browser Support

○ Firefox 4

○ Internet Explorer 9

○ Safari 5

○ Chrome 5+

 

Function 7: Object.preventExtensions / Object.isExtensible

这个函数能把一个对象的属性锁住,让他不能扩展。

 

 

Js代码  收藏代码
  1. var product = { name : 'Foobar', rating : 3.5 };  
  2. Object.isExtensible(product); // true  
  3. Object.preventExtentions(product);  
  4. Object.isExtensible(product); // false  
  5. product.price = '$10.00'// doesn't work  
  6. product.price; // undefined  

 但是仅仅只是不能增加属性,他的值仍然是可以改的,而且这个属性也能够被delete

Browser Support

○ Firefox 4

○ Internet Explorer 9

○ Chrome 6+

 

Function 8: Object.seal / Object.isSealed

 

Seal一个对象意味着你无法增加删除属性,也无法把已经定义好的属性值指向一个accessor (a method or

function),反过来也是一样

 

 

Js代码  收藏代码
  1. var pet = { name : 'Browser', type : 'dog' };  
  2. Object.seal(pet);  
  3. pet.name = 'Oreo';  
  4. pet.age = 2; // doesn't work  
  5. pet.type = function () { /**/ }; // doesn't work  
  6. delete pet.name; // doesn't work  

 Browser Support

○ Firefox 4

○ Internet Explorer 9

○ Chrome 6+

 

Function 9: Object.freeze / Object.isFrozen

freeze一个对象,意味着你不能通过任何手段修改对象内容,他变成了完全只读的

 

Js代码  收藏代码
  1. var obj = { greeting : 'Hi!' };  
  2. Object.freeze(obj);  
  3. Object.isFrozen(obj); // true  

 

 

Browser Support

○ Firefox 4

○ Internet Explorer 9

○ Chrome 6+

 

Function 10: Array.isArray

很显然,这是一个判断是否是数组的函数

 

Js代码  收藏代码
  1. var names = ['Collis''Cyan'];  
  2. Array.isArray(names); // true  

 Browser Support

○ Firefox 4

○ Internet Explorer 9

○ Safari 5

○ Chrome 5+

○ Opera 10.5+

Function 11: Date.prototype.toJSON

提供了从Date类型转成json的方法。

Js代码  收藏代码
  1. new Date().toJSON(); // "2010-12-06T16:25:40.040Z"  
 

Function 12: Function.prototype.bind

你会发现这个函数的功能和下面的很相似

Js代码  收藏代码
  1. var arr1 = ['1''2''3'],  
  2. arr2 = ['4''5''6'];  
  3. // 等同于arr1.push(arr2);  
  4. Array.prototype.push.apply(arr1, arr2);  
  5. alert(arr1);  

 bind和上面的不同之处在于apply是直接执行的,而bind只是绑定函数内部的this,并且将函数返回

Js代码  收藏代码
  1. var tooltip = { text: 'Click here to . . . ' },  
  2. overlay = { text: 'Please enter the number of attendees' };  
  3. function showText () {  
  4.      // really, do something more useful here  
  5.      alert(this.text);  
  6. }  
  7. tooltip.show = showText.bind(tooltip);  
  8. tooltip.show();  
  9. overlay.show = showText.bind(overlay);  
  10. overlay.show();  
 Browser Support

○ Firefox 4

○ Internet Explorer 9

○ Chrome 7+

 

Function 13: Date.now()

大致这个函数就是等同于new Date().getTime() or +new Date,不是什么大的改动

 

Function 14: Object.getPrototypeOf

这个函数提供了从通过Object.create得到的对象中提取原型的方法,当然,如果这个对象是通过老的new

function的方法创造出来的,那也可以通过这个方法得到原型

 

Js代码  收藏代码
  1. var Dog = {  
  2.      name : 'dog',  
  3.      paws : 4,  
  4.      hungry : false,  
  5.      speak : function () { return 'Woof!'; }  
  6. };  
  7. var dog = Object.create(Dog);  
  8. // true  
  9. alert(Object.getPrototypeOf(dog) === Dog);  
  10. // 老方法判断  
  11. function Cat() {}  
  12. // true  
  13. alert(Object.getPrototypeOf(new Cat()) === Cat.prototype);  

 

Function 15: String.prototype.trim

用来去除字符串两边的空格

Js代码  收藏代码
  1. var origin = " foo ";  
  2. document.write(origin.trim());  

 

Function 16: Array.prototype.indexOf

这个函数用来返回查找的对象在数组中第一次出现的index

他有两个参数,第一个参数是要查找的对象,第二个参数是查找的起始位置

Js代码  收藏代码
  1. var array = [2, 5, 9];  
  2. var index = array.indexOf(2);  
  3. // index is 0  
  4. index = array.indexOf(7);  
  5. // index is -1  
  6. var element = 5;  
  7. var indices = [];  
  8. var idx = array.indexOf(element);  
  9. while (idx != -1) {  
  10.       indices.push(idx);  
  11.       idx = array.indexOf(element, idx + 1);  
  12. }  

 当然如果浏览器没有支持indexOf,你可以用以下方法实现

Js代码  收藏代码
  1. if (!Array.prototype.indexOf) {  
  2.       Array.prototype.indexOf = function(searchElement /*, fromIndex */) {  
  3.             "use strict";  
  4.             if (this === void 0 || this === null)  
  5.                   throw new TypeError();  
  6.             var t = Object(this);  
  7.             var len = t.length >>> 0;  
  8.             if (len === 0)  
  9.                   return -1;  
  10.             var n = 0;  
  11.             if (arguments.length > 0) {  
  12.                   n = Number(arguments[1]);  
  13.                   if (n !== n)  
  14.                         n = 0;  
  15.                   else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))  
  16.                         n = (n > 0 || -1) * Math.floor(Math.abs(n));  
  17.             }  
  18.             if (n >= len)  
  19.                   return -1;  
  20.             var k = n >= 0  
  21.                         ? n : Math.max(len - Math.abs(n), 0);  
  22.             for (; k < len; k++) {  
  23.                   if (k in t && t[k] === searchElement)  
  24.                         return k;  
  25.             }  
  26.             return -1;  
  27.       };  
  28. }  
 

Function 17: Array.prototype.lastIndexOf

用法和16相似,取得最后一次出现的index

如果浏览器没有实现此方法,你可以通过这种方式实现

 

 

Java代码  收藏代码
  1. if (!Array.prototype.indexOf) {  
  2.       Array.prototype.indexOf = function(searchElement /*, fromIndex */) {  
  3.             "use strict";  
  4.   
  5.             if (this === void 0 || this === null)  
  6.                 throw new TypeError();  
  7.   
  8.             var t = Object(this);  
  9.             var len = t.length >>> 0;  
  10.             if (len === 0)  
  11.                 return -1;  
  12.   
  13.             var n = 0;  
  14.             if (arguments.length > 0) {  
  15.                 n = Number(arguments[1]);  
  16.                 if (n !== n)  
  17.                     n = 0;  
  18.                 else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))  
  19.                     n = (n > 0 || -1) * Math.floor(Math.abs(n));  
  20.             }  
  21.   
  22.             if (n >= len)  
  23.                 return -1;  
  24.   
  25.             var k = n >= 0  
  26.                     ? n : Math.max(len - Math.abs(n), 0);  
  27.   
  28.             for (; k < len; k++) {  
  29.                 if (k in t && t[k] === searchElement)  
  30.                 return k;  
  31.             }  
  32.             return -1;  
  33.       };  
  34. }  
  35.   
  36. Function 17: Array.prototype.lastIndexOf  
  37. 用法和16相似,取得最后一次出现参数的index  
  38. 如果浏览器没有实现此方法,你可以通过这种方式实现  
  39.     if (!Array.prototype.lastIndexOf) {  
  40.         Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {  
  41.             "use strict";  
  42.   
  43.             if (this === void 0 || this === null)  
  44.                 throw new TypeError();  
  45.   
  46.             var t = Object(this);  
  47.             var len = t.length >>> 0;  
  48.             if (len === 0)  
  49.                 return -1;  
  50.   
  51.             var n = len;  
  52.             if (arguments.length > 0) {  
  53.                 n = Number(arguments[1]);  
  54.                 if (n !== n)  
  55.                     n = 0;  
  56.                 else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))  
  57.                     n = (n > 0 || -1) * Math.floor(Math.abs(n));  
  58.             }  
  59.   
  60.             var k = n >= 0  
  61.                     ? Math.min(n, len - 1)  
  62.                     : len - Math.abs(n);  
  63.   
  64.             while (k >= 0) {  
  65.                 if (k in t && t[k] === searchElement)  
  66.                         return k;  
  67.                     }  
  68.                     return -1;  
  69.           };  
  70.     }  

 

 

 

Function 18: Array.prototype.every

 

对于数组中的每一项都执行某个callback function,这个function的参数为当前数组元素,当前元素index,整个数组。当function中返回为false的时候,停止循环数组。仅当返回为true的时候继续循环

 

Js代码  收藏代码
  1. function isBigEnough(element, index, array) {  
  2.     return (element >= 10);  
  3. }  
  4. var passed = [12, 5, 8, 130, 44].every(isBigEnough);  
  5. // passed is false  
  6. passed = [12, 54, 18, 130, 44].every(isBigEnough);  
  7. // passed is true  

 

 当浏览器没有实现此方法时,可以用以下方式代替

 

Js代码  收藏代码
  1. if (!Array.prototype.every) {  
  2.     Array.prototype.every = function(fun /*, thisp */) {  
  3.             "use strict";  
  4.   
  5.             if (this === void 0 || this === null)  
  6.                   throw new TypeError();  
  7.   
  8.             var t = Object(this);  
  9.             var len = t.length >>> 0;  
  10.             if (typeof fun !== "function")  
  11.                    throw new TypeError();  
  12.   
  13.             var thisp = arguments[1];  
  14.             for (var i = 0; i < len; i++) {  
  15.                     if (i in t && !fun.call(thisp, t[i], i, t))  
  16.                         return false;  
  17.             }  
  18.   
  19.             return true;  
  20.     };  
  21. }  

 

 

 

Function 19: Array.prototype.some

大致意思和every有些相似,当数组中有一个元素符合要求,就会返回true。所以callback中,一旦返回true,就不再循环,返回false则继续循环。

 

Js代码  收藏代码
  1. function isBigEnough(element, index, array) {  
  2.   return (element >= 10);  
  3. }  
  4. var passed = [2, 5, 8, 1, 4].some(isBigEnough);  
  5. // passed is false  
  6. passed = [12, 5, 8, 1, 4].some(isBigEnough);  
  7. // passed is true  

 

 

 

当浏览器不支持的时候,你可以用以下代码代替

 

Java代码  收藏代码
  1. if (!Array.prototype.some) {  
  2.     Array.prototype.some = function(fun /*, thisp */) {  
  3.             "use strict";  
  4.   
  5.             if (this === void 0 || this === null)  
  6.                     throw new TypeError();  
  7.   
  8.             var t = Object(this);  
  9.             var len = t.length >>> 0;  
  10.             if (typeof fun !== "function")  
  11.                     throw new TypeError();  
  12.   
  13.             var thisp = arguments[1];  
  14.             for (var i = 0; i < len; i++) {  
  15.             if (i in t && fun.call(thisp, t[i], i, t))  
  16.                 return true;  
  17.             }  
  18.   
  19.             return false;  
  20.     };  
  21. }  

 

 

 

Function 20: Array.prototype.forEach

 

此函数对数组的所有元素循环执行一个callback function

 

Js代码  收藏代码
  1.        function printElt(element, index, array) {  
  2.     print("[" + index + "] is " + element); // assumes print is already defined  
  3. }  
  4. [2, 5, 9].forEach(printElt);  
  5. // Prints:  
  6. // [0] is 2  
  7. // [1] is 5  
  8. // [2] is 9  

 

 当浏览器没有实现的时候,你可以通过如下方法代替

 

 

 

Js代码  收藏代码
  1. if (!Array.prototype.forEach) {  
  2.     Array.prototype.forEach = function(fun /*, thisp */) {  
  3.             "use strict";  
  4.   
  5.             if (this === void 0 || this === null)  
  6.                     throw new TypeError();  
  7.   
  8.             var t = Object(this);  
  9.             var len = t.length >>> 0;  
  10.             if (typeof fun !== "function")  
  11.                     throw new TypeError();  
  12.   
  13.             var thisp = arguments[1];  
  14.             for (var i = 0; i < len; i++) {  
  15.             if (i in t)  
  16.                 fun.call(thisp, t[i], i, t);  
  17.             }  
  18.     };  
  19. }  
 

 

Function 21: Array.prototype.map

循环数组每个元素,用于执行callback,之后返回循环结果作为一个新数组,而原数组不变.

Sample1:

 

Js代码  收藏代码
  1. function makePseudoPlural(single) {  
  2.     return single.replace(/o/g, "e");  
  3. }  
  4.   
  5. var singles = ["foot""goose""moose"];  
  6. var plurals = singles.map(makePseudoPlural);  
  7. // plurals is ["feet", "geese", "meese"]  
  8. // singles is unchanged<span style="white-space: normal;"> </span>  

 

Sample2

 

 

Js代码  收藏代码
  1. var numbers = [1, 4, 9];  
  2. var roots = numbers.map(Math.sqrt);  
  3. // roots is now [1, 2, 3]  
  4. // numbers is still [1, 4, 9]  

如果浏览器没有实现,则可以用如下方法代替

 

Java代码  收藏代码
  1. if (!Array.prototype.map) {  
  2.     Array.prototype.map = function(fun /*, thisp */) {  
  3.             "use strict";  
  4.   
  5.             if (this === void 0 || this === null)  
  6.                   throw new TypeError();  
  7.   
  8.             var t = Object(this);  
  9.             var len = t.length >>> 0;  
  10.             if (typeof fun !== "function")  
  11.                   throw new TypeError();  
  12.   
  13.             var res = new Array(len);  
  14.             var thisp = arguments[1];  
  15.         for (var i = 0; i < len; i++) {  
  16.                    if (i in t)  
  17.                          res[i] = fun.call(thisp, t[i], i, t);  
  18.         }  
  19.   
  20.         return res;  
  21. };  

 

 

 

Function 22: Array.prototype.filter

 

从数组中筛选出符合callback条件的元素,如果callback中返回true,则此元素会被加入到新数组中

 

Js代码  收藏代码
  1. function isBigEnough(element, index, array) {  
  2.     return (element >= 10);  
  3. }  
  4. // 12, 130, 44  
  5. var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);  

 

 如果浏览器没有实现,则可以用如下方式代替:

 

Js代码  收藏代码
  1. if (!Array.prototype.filter) {  
  2.     Array.prototype.filter = function(fun /*, thisp */) {  
  3.         "use strict";  
  4.   
  5.             if (this === void 0 || this === null)  
  6.                     throw new TypeError();  
  7.   
  8.             var t = Object(this);  
  9.             var len = t.length >>> 0;  
  10.             if (typeof fun !== "function")  
  11.                     throw new TypeError();  
  12.   
  13.             var res = [];  
  14.             var thisp = arguments[1];  
  15.             for (var i = 0; i < len; i++) {  
  16.                     if (i in t) {  
  17.                     var val = t[i]; // in case fun mutates this  
  18.                     if (fun.call(thisp, val, i, t))  
  19.                         res.push(val);  
  20.                 }  
  21.         }  
  22.         return res;  
  23.     };  
  24. }  
 

 

Function 23: Array.prototype.reduce

 

这个函数有两个参数,第一个为callback function,第二个为初始值。

Callback function的格式为:

.reduce(function(previousValue, currentValue, index, array){ // ...})

 

 

如果没有设置初始值, previousValue从第一个元素开始, currentValue从第二个元素开始循环。 总共循环Array.prototype.length – 1次。如果设置了初始值,previousValue从初始值开始,currentValue从第一个元素开始循环。 总共循环Array.prototype.length次。 最后返回最后一次callback function调用的结果. Sample:
Js代码  收藏代码
  1. var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; });  
  2. // total == 6  
  3.   
  4. var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {  
  5.     return a.concat(b);  
  6. });  
  7. // flattened is [0, 1, 2, 3, 4, 5]  
 

 

 

如果浏览器没有实现,则可用以下代码代替

 

 

 

 

 

Js代码  收藏代码
  1. if (!Array.prototype.reduce) {  
  2.     Array.prototype.reduce = function(fun /*, initialValue */) {  
  3.             "use strict";  
  4.   
  5.             if (this === void 0 || this === null)  
  6.                    throw new TypeError();  
  7.   
  8.         var t = Object(this);  
  9.             var len = t.length >>> 0;  
  10.             if (typeof fun !== "function")  
  11.                    throw new TypeError();  
  12.   
  13.             // no value to return if no initial value and an empty array  
  14.             if (len == 0 && arguments.length == 1)  
  15.                    throw new TypeError();  
  16.   
  17.             var k = 0;  
  18.             var accumulator;  
  19.             if (arguments.length >= 2) {  
  20.                    accumulator = arguments[1];  
  21.             } else {  
  22.                    do {  
  23.                     if (k in t) {  
  24.                         accumulator = t[k++];  
  25.                         break;  
  26.                     }  
  27.   
  28.                     // if array contains no values, no initial value to return  
  29.                         if (++k >= len)  
  30.                         throw new TypeError();  
  31.                     } while (true);  
  32.             }  
  33.   
  34.             while (k < len) {  
  35.                     if (k in t)  
  36.                     accumulator = fun.call(undefined, accumulator, t[k], k, t);  
  37.                     k++;  
  38.             }  
  39.   
  40.             return accumulator;  
  41.     };  
  42. }  
 

 

 

Function 24: Array.prototype.reduceRight

 

这个函数有两个参数,第一个为callback function,第二个为初始值。

 

Callback function的格式为:

.reduce(function(previousValue, currentValue, index, array){ // ... })

 

 

 

 

如果没有设置初始值, previousValue从最后一个元素开始, currentValue从倒数第二个元素开始循环。 总共循环Array.prototype.length – 1次。 如果设置了初始值,previousValue从初始值开始,currentValue从最后一个元素开始循环。 总共循环Array.prototype.length次。 最后返回最后一次callback function调用的结果.
Sample
Js代码  收藏代码
  1. var total = [0, 1, 2, 3].reduceRight(function(a, b) { return a + b; });  
  2. //total == 6  
  3.   
  4. var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) {  
  5.     return a.concat(b);  
  6. }, []);  
  7. // flattened is [4, 5, 2, 3, 0, 1]  
 如果浏览器没有实现,则可以用如下代码代替
Js代码  收藏代码
  1. if (!Array.prototype.reduceRight) {  
  2.     Array.prototype.reduceRight = function(callbackfn /*, initialValue */) {  
  3.             "use strict";  
  4.   
  5.             if (this === void 0 || this === null)  
  6.                     throw new TypeError();  
  7.   
  8.             var t = Object(this);  
  9.             var len = t.length >>> 0;  
  10.             if (typeof callbackfn !== "function")  
  11.                     throw new TypeError();  
  12.   
  13.             // no value to return if no initial value, empty array  
  14.             if (len === 0 && arguments.length === 1)  
  15.                     throw new TypeError();  
  16.   
  17.             var k = len - 1;  
  18.             var accumulator;  
  19.             if (arguments.length >= 2) {  
  20.                     accumulator = arguments[1];  
  21.             } else {  
  22.                     do {  
  23.                         if (k in this) {  
  24.                         accumulator = this[k--];  
  25.                         break;  
  26.                     }  
  27.   
  28.                     // if array contains no values, no initial value to return  
  29.                         if (--k < 0)  
  30.                                 throw new TypeError();  
  31.                      } while (true);  
  32.             }  
  33.   
  34.             while (k >= 0) {  
  35.                       if (k in t)  
  36.                     accumulator = callbackfn.call(undefined, accumulator, t[k], k, t);  
  37.                       k--;  
  38.             }  
  39.   
  40.         return accumulator;  
  41.     };  
  42. }  

  

posted @ 2012-09-09 10:28  awp110  阅读(377)  评论(0编辑  收藏  举报