gpt4 book ai didi

javascript - 输入字符串和数组以运行。数组中出现匹配字符串的输出索引

转载 作者:行者123 更新时间:2023-11-30 14:03:00 27 4
gpt4 key购买 nike

<分区>

我有一个字符串数组,我正在尝试定义一个函数,其中输入字符串“xyz”将搜索数组并返回索引。每次调用该函数时,“xyz”都会不同。

我试过这个(JavaScript):

var data = ["abc","def","ghi","jkl","mno"];
\\ this array is actually much longer

look = function(a){return a = this;}
\\ at first I was trying data.findIndex("xyz")
\\ but Chrome Dev. tools said "xyz" is not a function

Params = function(x="abc"){
y = data.findIndex(look,x);
return y;
}

\\ Params("abc") should return 0
\\ Params("def") should return 1
\\ Params("ghi") should return 2
\\ etc.

我知道我可以使用 for 循环来完成此操作,并循环遍历“数据”中的所有值,但这似乎效率不高。有没有更好的办法?我是否误解了“findIndex”方法?

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