为什么findIndex返回undefined而不是数组中的元素数?

时间:2019-05-03 21:17:04

标签: javascript arrays ecmascript-6

我想运行功能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"));

2 个答案:

答案 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"));