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 给定一个已经排好序的数组 ...
随机推荐
- Python学习笔记第二十七周(Bootstrap)
目录: 全局样式 一.栅格系统 二.表单 三.按钮 四.导航 五.按钮组 六.面板 七.表格 八.分页 九.排版 十.图片 十一.辅助类 十二.响应式工具 组件 内容: 前言: 首先通过https: ...
- [LeetCode&Python] Problem 674. Longest Continuous Increasing Subsequence
Given an unsorted array of integers, find the length of longest continuousincreasing subsequence (su ...
- ggplot2 multiply graphs on one figure
library(ggplot2)library(grid)grid.newpage()pushViewport(viewport(layout = grid.layout(1,2)))vplayout ...
- 渲染标签 - v-text
<!DOCTYPE html><html><head> <meta charset="utf-8"> <title ...
- Arch Linux root密码忘记了怎么办
https://wiki.archlinux.org/index.php/Reset_root_password_(简体中文)https://wiki.archlinux.org/index.php/ ...
- Head First 设计模式 (Eric Freeman / Elisabeth Freeman / Kathy Sierra / Bert Bates 著)
1. 欢迎来到设计模式世界:设计模式入门 (已看) 策略模式 定义了算法族,分别分装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户. 设计原则 找出应用中可能需要变化之处,把它们 ...
- 第1章 Java语言概述--HelloWorld--环境搭建
SE学什么 第1章 Java语言概述 第2章 基本语法 第3章 数组 第4章 面向对象编程(上) 第5章 面向对象编程(中) 第6章 面向对象编程(下) 第7章 异常处理 第8章 枚举类&注解 ...
- shell脚本实现定时备份某文件
1:目标 实现在图像化界面输入需要备份的源文件路径.目标路径,定时的时间.然后通过输入的信息,把需要备份的源文件打包放到指定的目标路径下以执行定时任务的时间为子目录 把/she ...
- 汉语言处理工具pyhanlp的拼音转换与字符正则化
汉字转拼音 HanLP中的汉字转拼音功能也十分的强大. 说明: l HanLP不仅支持基础的汉字转拼音,还支持声母.韵母.音调.音标和输入法首字母首声母功能. l HanLP能够识别多音字,也能给繁体 ...
- linux nodejs
scp node-v8.15.0-linux-x64.tar.gz root@10.88.248.231:/lngoa tar -zxvf node-v8.15.0-linux-x64.tar.gz ...