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 in | JavaScript 1.6 |
ECMAScript Edition | ECMAScript 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,整个数组将被查找)
- 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) { // shortcut for verifying if it's NaN
- n = 0;
- } else if (n !== 0 && n !== Infinity && n !== -Infinity) {
- 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;
- }
- }
- var array = [2, 5, 9];
- var index = array.indexOf(2);
- // index is 0
- index = array.indexOf(7);
- // index is -1
浏览器兼容性: