Array indexOf and lastIndexOf method

参见https://developer.mozilla.org/en-US/docs/JavaScript/Reference/global_objects/array/indexof

array.indexOf(searchElement[, fromIndex])

接受一个搜索值(searchElement),将其与数组(array)中的每个元素比较。如果找到该值,返回表示该数组元素的一个索引。如果没有找到,返回-1。

由于IE8不支持indexof,Mozilla针对这一函数的解决方案:

 1 if (!Array.prototype.indexOf) {
 2     Array.prototype.indexOf = function (searchElement , fromIndex ) {
 3         "use strict";
 4         if (this == null) {
 5             throw new TypeError();
 6         }
 7         var t = Object(this);
 8         var len = t.length >>> 0;
 9         if (len === 0) {
10             return -1;
11         }
12         var n = 0;
13         if (arguments.length > 1) {
14             n = Number(arguments[1]);
15             if (n != n) { // shortcut for verifying if it's NaN
16                 n = 0;
17             } else if (n != 0 && n != Infinity && n != -Infinity) {
18                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
19             }
20         }
21         if (n >= len) {
22             return -1;
23         }
24         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
25         for (; k < len; k++) {
26             if (k in t && t[k] === searchElement) {
27                 return k;
28             }
29         }
30         return -1;
31     }
32 }
33 
34 var array = [2, 5, 9];
35 var index = array.indexOf(5); // index is assigned 0
36 alert(index);
37 //index = array.indexOf(7); // index is assigned -1

 

array.lastIndexOf(searchElement[, fromIndex]);

 1 if (!Array.prototype.lastIndexOf)
 2 {
 3   Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/)
 4   {
 5     "use strict";
 6 
 7     if (this == null)
 8       throw new TypeError();
 9 
10     var t = Object(this);
11     var len = t.length >>> 0;
12     if (len === 0)
13       return -1;
14 
15     var n = len;
16     if (arguments.length > 1)
17     {
18       n = Number(arguments[1]);
19       if (n != n)
20         n = 0;
21       else if (n != 0 && n != (1 / 0) && n != -(1 / 0))
22         n = (n > 0 || -1) * Math.floor(Math.abs(n));
23     }
24 
25     var k = n >= 0
26           ? Math.min(n, len - 1)
27           : len - Math.abs(n);
28 
29     for (; k >= 0; k--)
30     {
31       if (k in t && t[k] === searchElement)
32         return k;
33     }
34     return -1;
35   };
36 }

 

 

posted @ 2013-05-09 22:56  Laborc_L  阅读(232)  评论(0编辑  收藏  举报