我有一个字符串数组,并且我试图定义一个函数,在该函数中,输入字符串“ 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”方法吗?
答案 0 :(得分:2)
const strings = ["abc","def","ghi","jkl","mno"];
const find = string => strings.indexOf(string)
find("abc") //return 0
答案 1 :(得分:0)
使用array.indexOf,例如:
Params = function(x) {
y = data.indexOf(x);
return y;
}