indexOf() 如何判断一个元素在指定数组中是否存在? 找出指定元素出现的所有位置? indexOf()方法 是正序查找,lastIndexOf()是倒叙查找
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()是倒叙查找的更多相关文章
- php判断一个值是否在一个数组中,区分大小写-也可以判断是否在键中
function in_array_case($value,$array){ return in_array(strtolower($value),array_map('strtolower',$ar ...
- 【JS】【6】判断一个元素是否在数组中
摘要: 有三种方式: 1,jquery的inArray方法 2,数组的indexOf方法 3,普通的for循环方法 正文: 1,jquery的inArray方法 /** * @param {Objec ...
- js判断一个元素是否在数组中
js判断一个元素是否在数组中 var arr = ['a','s','d','f']; console.info(isInArray(arr,'a'));//循环的方式 function isInAr ...
- js 数组 添加或删除 元素 splice 创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素 filter
里面可以用 箭头函数 splice 删除 增加 数组 中元素 操作数组 filter 创建新数组 检查指定数组中符合条件的所有元素
- 用JS编写一个函数,返回数组中重复出现过的元素
用JS编写一个函数,返回数组中重复出现过的元素,见下面的代码: , , , , , , , ]; var getRepeat = function (arr) { var obj = {}; , le ...
- 如何判断一个变量是否为数组(isArray)
在我们平时的工作中经常会用到如何判断一个变量是否为数组.常用的方法很多,有用常用框架里面的,isArray.但是关于这个isArray的实现,各有不同. 常用的方法有如下几种 1.instanceof ...
- JavaScript 用七种方式教你判断一个变量是否为数组类型
JavaScript 如何判断一个变量是否为数组类型 引言 正文 方法一 方法二 方法三 方法四 方法五 方法六 方法七 结束语 引言 我们如何判断一个变量是否为数组类型呢? 今天来给大家介绍七种方式 ...
- vuex中filter的使用 && 快速判断一个数是否在一个数组中
vue中filter的使用 computed: mapState({ items: state => state.items.filter(function (value, index, arr ...
- LeetCode 80 Remove Duplicates from Sorted Array II(移除数组中出现两次以上的元素)
题目链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/#/description 给定一个已经排好序的数组 ...
随机推荐
- 问题 Duplicate entry '0' for key 'PRIMARY'
今天使用了触发器,在一个表中执行增删改操作,然后在另一个表中执行相应的记录时,出现了这个问题 其实这个问题应该算是细节问题,有两种情况: 1.就是在插入数据的时候将id设置为not nul但是在插入数 ...
- Cannot find ./catalina.sh The file is absent or does not have execute permission This file is nee
从tomcat官网上下载了apache-tomcat-5.5.36.zip,在window xp系统里面解压以后,直接放在了linux服务器上. 进入tomcat/bin目录,执行启动的时候出现如下错 ...
- IOS Block代码块的定义与使用
代码块的本质是和其他的变量类似,不同的是,代码块存储的数据是一个函数体.使用代码块,你可以像调用其他标准函数一样的调用,可以传入参数,并得到返回值. 脱字符是代码块的语法标记.下图表示代码块的 ...
- 利用Aspectj实现Oval的自动参数校验
前言: Oval参数校验框架确实小巧而强大, 他通过注解的方式配置类属性, 然后通过Oval本身自带的工具类, 快速便捷执行参数校验. 但是工具类的校验需要额外的代码编写, 同时Oval对函数参数级的 ...
- c# 如何 使用共用体
用起来真的方便 转摘如下: C#借助FieldOffset属性实现共用体与强制类型转换 这两天被C#的强制类型转换弄得有点不习惯.事出如此. 在C#中,我打算读二进制文.文件的结构很简单,一连串的紧密 ...
- Tomcat下载和安装
一.Tomcat下载和安装 Tomcat 是一个免费的开放源代码的 Servlet 容器,它是 Apache 软件基金会的一个顶级项目,由 Apache,Sun和其他一些公司及个人共同开发而成.由于有 ...
- mysql与mysqli的区别
博客搬家了,欢迎大家关注,https://bobjin.com mysqli连接是永久连接,而MySQL是非永久连接. mysql连接:每当第二次使用的时候,都会重新打开一个新的进程. mysqli连 ...
- 二维数组的查找(JAVA)
二维数组查找 解题思路:找到该二维数组的特殊点,易知该二维数组左下角的那个点很特殊.从这个点往右看,数值都在变大:而往上看,数值都在变小.所以 我们可以将这个点的索引设为起点(i,j),当比目标数大时 ...
- Excel技巧--分隔工资条
要将上图的工资表,做成每行都带标题而且有空行间隔的工资条,可以这么做: 1.表格右侧添加一列数据列:输入1,2,选定,并双击单元格右下角形成一升序数字列: 2.再将该列复制,粘贴到该列末尾: 3.点一 ...
- 兼容ie,火狐的判断回车键js脚本
var event = window.event || arguments.callee.caller.arguments[0]; var keycode = event.keyCode || eve ...