JavaScript1.6新特性系列之indexOf(翻译)

JavaScript1.6新特性系列之 indexOf   

 

 

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 inJavaScript 1.6
ECMAScript EditionECMAScript 5th Edition

 

 

语法

 

 

 

 

 

 

 

 

 

array.indexOf(searchElement[, fromIndex])

 

 

 

 

 

    searchElement

 

          Element to locate in the array.  (所要在array定位的element)fromIndexThe 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.(开始查找的index,默认是0,会查找整个array.如果index大于或等于数组的长度,会返回-1,数组不会被查找。如果是负数,会按数组的偏移量(其实就是与数组的长度相加)进行查找 。注意即使index是负数,这个数组也会从开始查找到最后。如果计算后的Index小于0,整个数组将被查找)

  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.         }  
  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. }  
 
 
简单的例子
 
 
  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  


浏览器兼容性:


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值