您的位置:首页 > Web前端 > JavaScript

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

2012-04-24 18:24 351 查看

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

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
Object
,
TypeError
,
Number
,
Math.floor
,
Math.abs
, and
Math.max
have their original value.

view plainprint?

if (!Array.prototype.indexOf) {

Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {

"use strict";

if (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;

}

}

if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (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;
}
}


Examples

Example: Using indexOf

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

view plainprint?

var array = [2, 5, 9];

var index = array.indexOf(2);

// index is 0

index = array.indexOf(7);

// index is -1

var array = [2, 5, 9];
var index = array.indexOf(2);
// index is 0
index = array.indexOf(7);
// 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.

view plainprint?

var indices = [];

var idx = array.indexOf(element);

while (idx != -1) {

indices.push(idx);

idx = array.indexOf(element, idx + 1);

}

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


Browser compatibility

Based on Kangax's compat tables

/*<![CDATA[*/
$(function() {
$('.htab').append($('#compat-desktop'));
$('.htab').append($('#compat-mobile'));
var $items = $('.htab>ul>li');
$items.click(function() {
$items.removeClass('selected');
$(this).addClass('selected');
var index = $items.index($(this));
$('.htab>div').hide().eq(index).show();
}).eq(0).click();
});
/*]]>*/

Desktop

Mobile

FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support(Yes)(Yes)9(Yes)(Yes)
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support?????

See also

lastIndexOf

.pageText h1, .pageText h2, .pageText h3, .pageText h4, .pageText h5, .pageText h6 {
border-bottom: 1px solid #E0E0DC;
font-family: Georgia,Times,"Times New Roman",serif;
}
.pageText blockquote {
border-left: 5px solid #CCCCCC;
padding: 0 25px;
}
.pageText ul {
list-style: disc outside none;
padding-left: 22px;
}
.pageText ul ul {
list-style: circle outside none;
}
.pageText ol {
padding-left: 22px;
}
.pageText dt {
font-style: normal;
font-weight: bold;
}
.pageText dd {
margin-bottom: 0.5em;
padding-left: 15px;
}
.pageText table {
border-color: #CCCCCC;
}
.pageText th, .pageText td {
padding: 1px 3px;
}
.pageText thead th {
font-family: Georgia,Times,"Times New Roman",serif;
}
.pageText caption {
font-weight: bold;
}
.pageText pre {
background: none repeat scroll 0 0 #F6F6F2;
border: 1px dotted #CBC8B9;
font: 100% "Courier New","Andale Mono",monospace;
overflow: auto;
padding: 15px;
}
.pageText code, .pageText tt {
-moz-font-feature-settings: normal;
-moz-font-language-override: normal;
font-family: "Courier New","Andale Mono",monospace;
font-size: 100%;
font-size-adjust: none;
font-stretch: normal;
font-style: normal;
font-variant: normal;
font-weight: inherit;
line-height: normal;
}
.pageText pre code {
font-size: 100%;
}
.pageText strong code {
font-weight: inherit;
}
.pageText strong tt {
font-weight: inherit;
}
.pageText a code {
color: inherit;
}
.pageText img {
max-width: 100%;
}
.pageText {
-moz-transition: line-height 0.2s ease-in-out 0s;
line-height: inherit;
}
.pageText {
-moz-transition: line-height 0.2s ease-in-out 0s;
line-height: 1.572;
}

我的实现

Array.prototype.indexOf || (function(p){
p.indexOf = function(searchElem, fromIndex){
//如果this为空指针,抛出详细类型错误
if( this === 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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: