比较两个数组时找到第一个匹配值javascript [英] find the first matching value when comparing two arrays javascript

查看:68
本文介绍了比较两个数组时找到第一个匹配值javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图在品种数组和狗数组之间找到匹配项。如何返回找到的第一个匹配项。这是我似乎无法正常工作的原因,我完全找不到错误。谢谢

I'm trying to find a match between the breeds array and the dogs array. How can I return the first match that is found. This is what i have that doesn't seem to work and I cant quite find the error. Thanks

var dogs = ["pug", "husky", "hound", "poodle"];

function findTheBreed(dogs) {
    var breeds = ["terrier", "mix", "lab", "hound"];
 for(let i = 0; i < dogs.length; i++) {
   for (let b = 0; b < breeds.length; b++) {
     if(dogs[i] === breeds[b]) {
       return breeds[b]
      } else {
       return "no match"
      }
    }
   }
 }


推荐答案

您返回的是false在第一个不匹配项上,而您应该继续进行迭代。

You're returning false on the first non-match, whereas you should continue iterating.

返回不匹配 移至之后

jsfiddle

您也可以在此处使用 indexOf

function findTheBreed(dogs) {
    var breeds = ["terrier", "mix", "lab", "hound"];
    for(let i = 0; i < dogs.length; i++) {
      if(breeds.indexOf(dogs[i]) != -1){
      return dogs[i];
    }
  }   
  return "no match";
}

jsfiddle

另一种(我认为最好)的方法是使用 Array.filter 功能并检索全部匹配项数组。

One other (in my opinion the best) route would be to use the Array.filter functionality and retrieve the entire array of matches.

  var breeds = ["terrier", "mix", "lab", "hound", "snickerdoodle"];
    var filtered = breeds.filter(
    function (elem) {
      return dogs.indexOf(elem) != -1
    }
  );
  return filtered;

jsfiddle

这篇关于比较两个数组时找到第一个匹配值javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆