代码改变世界

【javascript基础】之【javascript1.6 Array 新增方法】之【indexOf】

2012-04-24 18:24  sniper007  阅读(317)  评论(0编辑  收藏  举报

 

Summary

Returns the first index at which a given element can be found in the array, or -1 if it is not present.

Method of Array
Implemented in JavaScript 1.6
ECMAScript Edition ECMAScript 5th Edition

Syntax

array.indexOf(searchElement[, fromIndex])

Parameters

searchElement
Element to locate in the array.
fromIndex
The index at which to begin the search. Defaults to 0, i.e. the whole array will be searched. If the index is greater than or equal to the length of the array, -1 is returned, i.e. the array will not be searched. If negative, it is taken as the offset from the end of the array. Note that even when the index is negative, the array is still searched from front to back. If the calculated index is less than 0, the whole array will be searched.

Description

indexOf compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).

Compatibility

indexOf is a recent addition to the ECMA-262 standard; as such it may not be present in all browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing use of indexOf in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming ObjectTypeErrorNumber, Math.floor, Math.abs, and Math.max have their original value.  

  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 > 0) {  
  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. }  

Examples

Example: Using indexOf

The following example uses indexOf to locate values in an array.

  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  

Example: Finding all the occurrences of an element

The following example uses indexOf to find all the indices of an element in a given array, using push to add them to another array as they are found.

  1. var indices = [];  
  2. var idx = array.indexOf(element);  
  3. while (idx != -1) {  
  4.     indices.push(idx);  
  5.     idx = array.indexOf(element, idx + 1);  
  6. }  

Browser compatibility

Based on Kangax's compat tables

  • Desktop
  • Mobile
Feature Firefox (Gecko) Chrome Internet Explorer Opera Safari
Basic support (Yes) (Yes) 9 (Yes) (Yes)

 

See also

lastIndexOf

我的实现

Array.prototype.indexOf  || (function(p){
    p.indexOf = function(searchElem, fromIndex){
        //如果this为空指针,抛出详细类型错误
        ifthis === null ){
            throw "【Array.prototype.indexOf ERROR】不是数组!";
        }
        
        var len = this.length;
        fromIndex = Number( arguments[1] ) || 0;
        //算出查询开始位置
        
        fromIndex = fromIndex > 0 ?
                    Math.floor( fromIndex ) : 
                    Math.ceil( fromIndex );
        //如果开始为之比数组长度大,或者等于,返回-1
        if( fromIndex >= len ){
            return -1;
        }
        
        var start = fromIndex;
        
        if( fromIndex < 0 ){
            start = 0;
        }

        for( ; start < len; start++ ){
            var $item = this[start];
            if( $item === searchElem ){
                return start;
            }
        }
        
        return -1;
        
    };
})(Array.prototype);