我想运行功能search(“ something here”),然后接收该元素在数组中的位置。有什么想法吗?
const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];
function search(s){
const searchQuery = animals.findIndex(animal => {
return animal === s;
});
};
console.log(search("hippo"));
答案 0 :(得分:4)
您需要return searchQuery
:
const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];
function search(s) {
const searchQuery = animals.findIndex(animal => {
return animal === s;
});
return searchQuery;
};
console.log(search("hippo"));
您也可以完全摆脱searchQuery
,而只返回findIndex
调用:
const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];
function search(s) {
return animals.findIndex(animal => {
return animal === s;
});
};
console.log(search("hippo"));
答案 1 :(得分:1)
除了返回结果,您还可以使用Array#indexOf
。
function search(s) {
return animals.indexOf(s);
};
const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];
console.log(search("hippo"));