js Array.prototype.indexOf 获取元素在数组中的index

来源:互联网 发布:阿里云搭建个人博客 编辑:程序博客网 时间:2024/06/05 00:27

参看文档  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

用法:

从数组中获取查询元素的位置, 如果不存在则返回-1, 如果有多个重复元素,那么总是返回第一个元素

arr.indexOf(searchElemenmt  [,fromIndex])  


备注:

fromIndex 代表查询开始的索引, 可以是负值,eg: -2 从倒数第二个元素开始查找


eg:

查询数组中某个元素的所有的索引

var array = ['a', 'b', 'a', 'c', 'a', 'd', '1',1,'1'];function searchIndex(arr, element_search) {    var index = arr.indexOf(element_search);    console.log(index);    if (index === -1) {        return [];    }    var index_list = [];    while (index !== -1) {        index_list.push(index);        index = arr.indexOf(element_search, index+1);    }    return index_list;}var result = searchIndex(array, '1');console.log(result);

阅读全文
0 0