indexOf()方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。

let a = [2, 9, 7, 8, 9];
a.indexOf(2); // 0
a.indexOf(6); // -1
a.indexOf(7); // 2
a.indexOf(8); // 3
a.indexOf(9); // 1 if (a.indexOf(3) === -1) {
// element doesn't exist in array
}

语法

arr.indexOf(searchElement)
arr.indexOf(searchElement[, fromIndex = 0])

参数

searchElement
要查找的元素
fromIndex
开始查找的位置。如果该索引值大于或等于数组长度,意味着不会在数组里查找,返回-1。如果参数中提供的索引值是一个负值,则将其作为数组末尾的一个抵消,即-1表示从最后一个元素开始查找,-2表示从倒数第二个元素开始查找 ,以此类推。 注意:如果参数中提供的索引值是一个负值,仍然从前向后查询数组。如果抵消后的索引值仍小于0,则整个数组都将会被查询。其默认值为0.

返回值

首个被找到的元素在数组中的索引位置; 若没有找到则返回 -1

描述

indexOf 使用strict equality (无论是 ===, 还是 triple-equals操作符都基于同样的方法)进行判断 searchElement与数组中包含的元素之间的关系。

应用:使用indexOf方法确定多个值在数组中的位置。

 var array = [2, 5, 9];
array.indexOf(2); //
array.indexOf(7); // -1
array.indexOf(9, 2); //
array.indexOf(2, -1); // -1
array.indexOf(2, -3); //

应用:找出指定元素出现的所有位置

 var indices = [];
var array = ['a', 'b', 'a', 'c', 'a', 'd'];
var element = 'a';
var idx = array.indexOf(element);
while (idx != -1) {
indices.push(idx);
idx = array.indexOf(element, idx + 1);
}
console.log(indices);
// [0, 2, 4]

应用:判断一个元素是否在数组里,不在则更新数组

 function updateVegetablesCollection (veggies, veggie) {
if (veggies.indexOf(veggie) === -1) {
veggies.push(veggie);
console.log('New veggies collection is : ' + veggies);
} else if (veggies.indexOf(veggie) > -1) {
console.log(veggie + ' already exists in the veggies collection.');
}
} var veggies = ['potato', 'tomato', 'chillies', 'green-pepper']; // New veggies collection is : potato,tomato,chillies,green-papper,spinach
updateVegetablesCollection(veggies, 'spinach');
// spinach already exists in the veggies collection.
updateVegetablesCollection(veggies, 'spinach');

Polyfill

indexOf 在ECMA-262 标准 的第5版中被加入,但并非所有的浏览器都支持该方法。你可以在编写scripts时,在其开头使用以下代码,它能够允许你在没有本地支持的情况下使用indexOf方法。该算法符合ECMA-262第5版其中一项规定, 即假定 TypeError和 Math.abs 呈现它们原有的价值。

 // Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this == null) {
throw new TypeError('"this" is null or not defined');
} var O = Object(this); // 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // 4. If len is 0, return -1.
if (len === 0) {
return -1;
} // 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0; if (Math.abs(n) === Infinity) {
n = 0;
} // 6. If n >= len, return -1.
if (n >= len) {
return -1;
} // 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}

indexOf() 如何判断一个元素在指定数组中是否存在? 找出指定元素出现的所有位置? indexOf()方法 是正序查找,lastIndexOf()是倒叙查找的更多相关文章

  1. php判断一个值是否在一个数组中,区分大小写-也可以判断是否在键中

    function in_array_case($value,$array){ return in_array(strtolower($value),array_map('strtolower',$ar ...

  2. 【JS】【6】判断一个元素是否在数组中

    摘要: 有三种方式: 1,jquery的inArray方法 2,数组的indexOf方法 3,普通的for循环方法 正文: 1,jquery的inArray方法 /** * @param {Objec ...

  3. js判断一个元素是否在数组中

    js判断一个元素是否在数组中 var arr = ['a','s','d','f']; console.info(isInArray(arr,'a'));//循环的方式 function isInAr ...

  4. js 数组 添加或删除 元素 splice 创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素 filter

    里面可以用 箭头函数 splice         删除 增加 数组 中元素 操作数组 filter 创建新数组  检查指定数组中符合条件的所有元素

  5. 用JS编写一个函数,返回数组中重复出现过的元素

    用JS编写一个函数,返回数组中重复出现过的元素,见下面的代码: , , , , , , , ]; var getRepeat = function (arr) { var obj = {}; , le ...

  6. 如何判断一个变量是否为数组(isArray)

    在我们平时的工作中经常会用到如何判断一个变量是否为数组.常用的方法很多,有用常用框架里面的,isArray.但是关于这个isArray的实现,各有不同. 常用的方法有如下几种 1.instanceof ...

  7. JavaScript 用七种方式教你判断一个变量是否为数组类型

    JavaScript 如何判断一个变量是否为数组类型 引言 正文 方法一 方法二 方法三 方法四 方法五 方法六 方法七 结束语 引言 我们如何判断一个变量是否为数组类型呢? 今天来给大家介绍七种方式 ...

  8. vuex中filter的使用 && 快速判断一个数是否在一个数组中

    vue中filter的使用 computed: mapState({ items: state => state.items.filter(function (value, index, arr ...

  9. LeetCode 80 Remove Duplicates from Sorted Array II(移除数组中出现两次以上的元素)

    题目链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/#/description 给定一个已经排好序的数组 ...

随机推荐

  1. day 11 函数参数

    形参与实参 形参:就是形式参数,在函数定义时,写在括号里面指定的参数就是形式参数 实参:在调用函数时传入的参数就是实参 在调用函数时就会自动的把形参与实参绑定起来,然后调用结束之后,解除绑定关系 位置 ...

  2. 自动化测试-19.selenium定位之通过JS修改html写入日期数据以及从文本读取数据实战

    # -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.support.select import ...

  3. golang sync.Cond条件变量的使用

    cond.Wait()的操作实际上是对与cond绑定的锁先进行解锁,在等待通知:接收到通知后,会尝试加锁,加锁成功则唤醒否则继续等待通知: cond.Waite()前必须对关连锁加锁,否则panic ...

  4. 《CSS揭秘》之毛玻璃效果知识点

    实现代码: CodePen:毛玻璃效果 Dabblet:毛玻璃效果 HTML: <main> <blockquote> <em>"The only way ...

  5. Linux监控平台、安装zabbix、修改zabbix的admin密码

    1.Linux监控平台 2. zabbix监控 3.zabbix的安装下载:wget -c https://repo.zabbix.com/zabbix/3.4/rhel/7/x86_64/zabbi ...

  6. python函数之第一类对象

    目录 python函数之第一类对象 python函数之第一类对象 第一类对象(英语:First-class object)在计算机科学中指可以在执行期创造并作为参数传递给其他函数或存入一个变数的实体. ...

  7. PythonStudy——文件操作习题 Document operation exercises

    # 1.统计文件数据中字母e出现的次数(不区分大小写)# 文件内容:hello friend, can you speak English!# 结果:4# 分析:将文件内容读出,然后统计读出的字符串中 ...

  8. linux下insmod模块出现“Invalid parameters"

    在编译一个模块时,会出现WARNING:"函数名" undefined!,这 说明该模块所依赖的模块还没有加载进内核,需要先加载所依赖的模块. 当加载依赖模块后,使用insmod会 ...

  9. mongo数据的导入(mongoimport)和导出(mongoexport)

    1.导出数据可以使用命令: mongoexport -h dbhost -d dbname -c collectionName -o output 参数说明: -h 数据库地址 -d 指明使用的库 - ...

  10. globals和locals的区别

    Python的两个内置函数,locals 和globals,它们提供了基于字典的访问局部和全局变量的方式. 1.locals()是只读的.globals()不是.这里说的只读,是值对于原有变量的只读. ...