【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 in | JavaScript 1.6 |
ECMAScript Edition | ECMAScript 5th Edition |
Syntax
array.indexOf(searchElement[, fromIndex])
Parameters
searchElementElement to locate in the array.
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.
Description
indexOfcompares
searchElementto elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).
Compatibility
indexOfis 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
indexOfin 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.maxhave 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 usesindexOfto 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 usesindexOfto 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
Feature | Firefox (Gecko) | Chrome | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | 9 | (Yes) | (Yes) |
Feature | Firefox Mobile (Gecko) | Android | IE Mobile | Opera Mobile | Safari 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);
相关文章推荐
- 【javascript基础】之【javascript1.6 Array 新增方法】
- JavaScript 5 新增 Array 方法实现介绍
- JavaScript Array对象indexOf()方法的实现
- JavaScript Array对象扩展indexOf()方法
- JavaScript 1.6 引入了几个新的Array (数组)方法
- JavaScript ES5标准中新增的Array方法
- Core Javascript1.6的Array方法扩展
- Javascript 1.6 数组新增方法介绍之 forEach()
- javaScript高级教程(一)javaScript 1.6 Array 新增函数
- 数组Array和字符串String的indexOf方法,以及ES7(ES2016)中新增的Array.prototype.includes方法
- $.inArray()方法类似于JavaScript的原生.indexOf()方法
- JavaScript Array 对象常用方法
- JavaScript判断变量是否为数组的方法(Array)
- JavaScript (Array) map 方法
- javascript 学习小结 (二)新增小数取整各种方法 by FungLeo
- 5个数组Array方法: indexOf、filter、forEach、map、reduce使用实例
- javaScript array(数组)使用字符串作为数组下标的方法
- es6 数组对象新增方法 Array.from()将两类对象转为真正的数组
- Java基础:数组Array转成List的几种方法