ECMAScript5 新特性(四)

 

Function 17: Array.prototype.lastIndexOf

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

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

 

 

if (!Array.prototype.indexOf) {
	  Array.prototype.indexOf = function(searchElement /*, fromIndex */) {
	    	"use strict";

	    	if (this === void 0 || this === null)
	      		throw new TypeError();

	    	var t = Object(this);
	    	var len = t.length >>> 0;
	    	if (len === 0)
	      		return -1;

	    	var n = 0;
	    	if (arguments.length > 0) {
	      		n = Number(arguments[1]);
	      		if (n !== n)
	        		n = 0;
	      		else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
	        		n = (n > 0 || -1) * Math.floor(Math.abs(n));
	    	}

	    	if (n >= len)
	      		return -1;

	    	var k = n >= 0
	          		? n : Math.max(len - Math.abs(n), 0);

	    	for (; k < len; k++) {
	      		if (k in t && t[k] === searchElement)
	        	return k;
	    	}
	    	return -1;
	  };
}

Function 17: Array.prototype.lastIndexOf
用法和16相似,取得最后一次出现参数的index
如果浏览器没有实现此方法,你可以通过这种方式实现
	if (!Array.prototype.lastIndexOf) {
	  	Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
	    	"use strict";

	    	if (this === void 0 || this === null)
	      		throw new TypeError();

    		var t = Object(this);
    		var len = t.length >>> 0;
    		if (len === 0)
      			return -1;

    		var n = len;
    		if (arguments.length > 0) {
      			n = Number(arguments[1]);
      			if (n !== n)
        			n = 0;
      			else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
        			n = (n > 0 || -1) * Math.floor(Math.abs(n));
    		}

    		var k = n >= 0
          			? Math.min(n, len - 1)
          			: len - Math.abs(n);

    		while (k >= 0) {
      			if (k in t && t[k] === searchElement)
        		        return k;
    		        }
    		        return -1;
  	      };
	}

 

 

 

Function 18: Array.prototype.every

 

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

 

function isBigEnough(element, index, array) {
	return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].every(isBigEnough);
// passed is false
passed = [12, 54, 18, 130, 44].every(isBigEnough);
// passed is true

 

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

 

if (!Array.prototype.every) {
  	Array.prototype.every = function(fun /*, thisp */) {
    		"use strict";

    		if (this === void 0 || this === null)
      		      throw new TypeError();

    		var t = Object(this);
    		var len = t.length >>> 0;
    		if (typeof fun !== "function")
	      	       throw new TypeError();

	    	var thisp = arguments[1];
	    	for (var i = 0; i < len; i++) {
	      	        if (i in t && !fun.call(thisp, t[i], i, t))
	        	        return false;
	    	}

	    	return true;
  	};
}

 

 

 

Function 19: Array.prototype.some

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

 

	function isBigEnough(element, index, array) {
	  return (element >= 10);
	}
	var passed = [2, 5, 8, 1, 4].some(isBigEnough);
	// passed is false
	passed = [12, 5, 8, 1, 4].some(isBigEnough);
	// passed is true

 

 

 

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

 

if (!Array.prototype.some) {
  	Array.prototype.some = function(fun /*, thisp */) {
    		"use strict";

    		if (this === void 0 || this === null)
      		        throw new TypeError();

    		var t = Object(this);
    		var len = t.length >>> 0;
    		if (typeof fun !== "function")
      		        throw new TypeError();

    		var thisp = arguments[1];
    		for (var i = 0; i < len; i++) {
      		if (i in t && fun.call(thisp, t[i], i, t))
        		return true;
    		}

    		return false;
  	};
}

 

 

 

Function 20: Array.prototype.forEach

 

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

 

        function printElt(element, index, array) {
	    print("[" + index + "] is " + element); // assumes print is already defined
	}
	[2, 5, 9].forEach(printElt);
	// Prints:
	// [0] is 2
	// [1] is 5
	// [2] is 9

 

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

 

 

 

if (!Array.prototype.forEach) {
  	Array.prototype.forEach = function(fun /*, thisp */) {
    		"use strict";

    		if (this === void 0 || this === null)
      		        throw new TypeError();

    		var t = Object(this);
    		var len = t.length >>> 0;
    		if (typeof fun !== "function")
      		        throw new TypeError();

    		var thisp = arguments[1];
    		for (var i = 0; i < len; i++) {
      		if (i in t)
        		fun.call(thisp, t[i], i, t);
    		}
  	};
}
 

 

Function 21: Array.prototype.map

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

Sample1:

 

function makePseudoPlural(single) {
  	return single.replace(/o/g, "e");
}

var singles = ["foot", "goose", "moose"];
var plurals = singles.map(makePseudoPlural);
// plurals is ["feet", "geese", "meese"]
// singles is unchanged 

 

Sample2

 

 

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

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

 

if (!Array.prototype.map) {
  	Array.prototype.map = function(fun /*, thisp */) {
    		"use strict";

    		if (this === void 0 || this === null)
      		      throw new TypeError();

    		var t = Object(this);
    		var len = t.length >>> 0;
    		if (typeof fun !== "function")
      		      throw new TypeError();

    		var res = new Array(len);
    		var thisp = arguments[1];
 		for (var i = 0; i < len; i++) {
      		       if (i in t)
        	             res[i] = fun.call(thisp, t[i], i, t);
    	}

    	return res;
};

 

 

 

Function 22: Array.prototype.filter

 

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

 

function isBigEnough(element, index, array) {
	return (element >= 10);
}
// 12, 130, 44
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);

 

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

 

if (!Array.prototype.filter) {
	Array.prototype.filter = function(fun /*, thisp */) {
		"use strict";

	    	if (this === void 0 || this === null)
	      	        throw new TypeError();

	    	var t = Object(this);
	    	var len = t.length >>> 0;
	    	if (typeof fun !== "function")
	      	        throw new TypeError();

	    	var res = [];
	    	var thisp = arguments[1];
	    	for (var i = 0; i < len; i++) {
	      	        if (i in t) {
	        		var val = t[i]; // in case fun mutates this
	        		if (fun.call(thisp, val, i, t))
	          			res.push(val);
	    		}
		}
		return res;
	};
}
 

 

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:
var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; });
// total == 6

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
	return a.concat(b);
});
// flattened is [0, 1, 2, 3, 4, 5]
 

 

 

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

 

 

 

 

 

if (!Array.prototype.reduce) {
  	Array.prototype.reduce = function(fun /*, initialValue */) {
    		"use strict";

    		if (this === void 0 || this === null)
      		       throw new TypeError();

   	 	var t = Object(this);
    		var len = t.length >>> 0;
    		if (typeof fun !== "function")
      		       throw new TypeError();

    		// no value to return if no initial value and an empty array
    		if (len == 0 && arguments.length == 1)
      		       throw new TypeError();

    		var k = 0;
    		var accumulator;
    		if (arguments.length >= 2) {
      		       accumulator = arguments[1];
    		} else {
      		       do {
        			if (k in t) {
          				accumulator = t[k++];
          				break;
        			}

        			// if array contains no values, no initial value to return
       	 		        if (++k >= len)
          				throw new TypeError();
      		        } while (true);
    		}

    		while (k < len) {
      		        if (k in t)
        			accumulator = fun.call(undefined, accumulator, t[k], k, t);
      		        k++;
    		}

    		return accumulator;
	};
}
 

 

 

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
var total = [0, 1, 2, 3].reduceRight(function(a, b) { return a + b; });
//total == 6

var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) {
  	return a.concat(b);
}, []);
// flattened is [4, 5, 2, 3, 0, 1]
 如果浏览器没有实现,则可以用如下代码代替
if (!Array.prototype.reduceRight) {
  	Array.prototype.reduceRight = function(callbackfn /*, initialValue */) {
    		"use strict";

    		if (this === void 0 || this === null)
      		        throw new TypeError();

    		var t = Object(this);
    		var len = t.length >>> 0;
    		if (typeof callbackfn !== "function")
      		        throw new TypeError();

    		// no value to return if no initial value, empty array
    		if (len === 0 && arguments.length === 1)
      		        throw new TypeError();

    		var k = len - 1;
    		var accumulator;
    		if (arguments.length >= 2) {
      		        accumulator = arguments[1];
    		} else {
	      	        do {
	      	  	        if (k in this) {
	          			accumulator = this[k--];
	          			break;
	        		}

	        		// if array contains no values, no initial value to return
	 	       	        if (--k < 0)
	      	    		        throw new TypeError();
	      	         } while (true);
	    	}

    		while (k >= 0) {
      		          if (k in t)
        			accumulator = callbackfn.call(undefined, accumulator, t[k], k, t);
      		          k--;
    		}

		return accumulator;
  	};
}
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值