猿问

如何找到带有值的数组索引?

说我有这个


imageList = [100,200,300,400,500];

这给了我


[0]100 [1]200 等等


JavaScript中有什么方法可以返回带有值的索引?


即我想要200的索引,我得到1。


三国纷争
浏览 624回答 3
3回答

慕婉清6462132

您可以使用indexOf:var imageList = [100,200,300,400,500];var index = imageList.indexOf(200); // 1如果无法在数组中找到值,则将得到-1。

蝴蝶刀刀

对于对象阵列使用map与indexOf:var imageList = [   {value: 100},   {value: 200},   {value: 300},   {value: 400},   {value: 500}];var index = imageList.map(function (img) { return img.value; }).indexOf(200);console.log(index);在现代浏览器中,您可以使用findIndex:var imageList = [   {value: 100},   {value: 200},   {value: 300},   {value: 400},   {value: 500}];var index = imageList.findIndex(img => img.value === 200);console.log(index);它是ES6的一部分,并受 Chrome,FF,Safari和Edge支持

牛魔王的故事

这是在javascript中的复杂数组中查找值索引的另一种方法。希望确实能帮助到别人。让我们假设我们有一个如下的JavaScript数组,var studentsArray =&nbsp; &nbsp; &nbsp;[&nbsp; &nbsp; {&nbsp; &nbsp; "rollnumber": 1,&nbsp; &nbsp; "name": "dj",&nbsp; &nbsp; "subject": "physics"&nbsp; &nbsp;},&nbsp; &nbsp;{&nbsp; &nbsp;"rollnumber": 2,&nbsp; "name": "tanmay",&nbsp; "subject": "biology"&nbsp; &nbsp;},&nbsp; {&nbsp; &nbsp;"rollnumber": 3,&nbsp; &nbsp;"name": "amit",&nbsp; &nbsp;"subject": "chemistry"&nbsp; &nbsp;},&nbsp; ];现在,如果我们需要选择数组中的特定对象。让我们假设我们要查找名称为Tanmay的学生的索引。我们可以通过遍历数组并比较给定键的值来做到这一点。function functiontofindIndexByKeyValue(arraytosearch, key, valuetosearch) {&nbsp; &nbsp; for (var i = 0; i < arraytosearch.length; i++) {&nbsp; &nbsp; if (arraytosearch[i][key] == valuetosearch) {&nbsp; &nbsp; return i;&nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return null;&nbsp; &nbsp; }您可以使用该函数来查找特定元素的索引,如下所示,var index = functiontofindIndexByKeyValue(studentsArray, "name", "tanmay");alert(index);
随时随地看视频慕课网APP
我要回答