gpt4 book ai didi

javascript - 获取数组中搜索结果的索引

转载 作者:行者123 更新时间:2023-12-02 21:43:31 25 4
gpt4 key购买 nike

我有以下代码:

var member_data_list = [
["adrian", "test", Number(9)],
["supler", "test", Number(2.3)],
["franz", "test", Number(2.5)],
["drucker", "test", Number(9.6)],
];

if (exists(member_data_list, "franz")) {
//HERE I NEED TO GET THE INDEX OF MEMBER_DATA_LIST[?]
//EXAMPLE: if (exists(member_data_list, "franz")) => RESULT => 2 (MEMBER_DATA_LIST[2])
console.log("NAME IS IN ARRAY AT INDEX " + "?");
}

function exists(arr, search) {
return arr.some(row => row.includes(search));
}

如何获取该数组中名称的索引?

最佳答案

一种解决方案是通过 .find() 获取元素,然后使用 .indexOf()。例如:

var member_data_list = [
["adrian", "test", Number(9)],
["supler", "test", Number(2.3)],
["franz", "test", Number(2.5)],
["drucker", "test", Number(9.6)],
];

if (exists(member_data_list, "franz")) {
var found = member_data_list.find(row => row[0] === "franz")
var index = member_data_list.indexOf(found)

// if the element is exists then index's value will be greater than -1
if (index > -1) {
console.log("NAME IS IN ARRAY AT INDEX " + index)
}
}

function exists(arr, search) {
return arr.some(row => row.includes(search));
}

关于javascript - 获取数组中搜索结果的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60322694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com