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. 使用element-ui 遇到的问题

    Pagination 分页 在使用分页的时候,每次切换pageSize的时候,需要把current-page置为1 重新加载数据. 但是当current-page !== 1的时候,修改current ...

  2. 剑指Offer 45. 扑克牌顺子 (其他)

    题目描述 LL今天心情特别好,因为他去买了一副扑克牌,发现里面居然有2个大王,2个小王(一副牌原本是54张^_^)...他随机从中抽出了5张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到的话,他决 ...

  3. python+flask开发小白第二天

    使用VSCode编译python web页面 1.先从最基础的说起吧,关于VSCode的使用: 运行python程序与运行java,c,c++程序一样,需要新建一个文件,第一个文件建议不要新建在本地的 ...

  4. box-shadow做出一条线两种颜色

    今天同事问我一个问题,说下图的效果是怎么实现的 我当时想都没有想说这不就是两条线嘛,他说是一条线用box-shadow做出来的,之前也没有遇到过,觉得很有意思就试了一把. 语法 box-shadow: ...

  5. Python学习笔记第二十七周(Bootstrap)

    目录: 全局样式 一.栅格系统 二.表单 三.按钮  四.导航 五.按钮组 六.面板 七.表格 八.分页 九.排版 十.图片 十一.辅助类 十二.响应式工具 组件 内容: 前言: 首先通过https: ...

  6. python import 包的路径以及相对路径加载的问题

    查看python当前系统import 命令时,系统支持的路径 除了当前目录之外,如下代码 即可查看import 包含的路径在哪些地方 参考链接 https://www.cnblogs.com/qing ...

  7. [LeetCode&Python] Problem 458. Poor Pigs

    There are 1000 buckets, one and only one of them contains poison, the rest are filled with water. Th ...

  8. XML一

    HTML(HyperText Markup Language),即超文本标记语言,是用于描述网页文档的一种描述标记语言.                                  而XML(E ...

  9. $\mathcal{OI}$生涯中的各种数论算法的证明

    嗯,写这个是因为我太弱了\(ORZ\). #\(\mathcal{\color{silver}{1 \ \ Linear \ \ Sieve \ \ Method \ \ of \ \ Prime}} ...

  10. 加载XML文件到系统中

    using System;using System.Data;using System.IO;using System.Xml;using System.Collections.Generic; na ...