3个数组中的哪个数组包含一个特定的值,然后使用该数组?Javascript

Which array among 3 arrays contain a specific value and then use that array? Javascript

本文关键字:数组 然后 Javascript 包含一 3个      更新时间:2023-09-26

我有三个数组:

northamerica = ["USA","Canada","Mexico"];
europe = ["France", "Germany", "Italy"];
africa = ["Morocco", "Ghana", "Madagascar"];

我想找出这3个数组中哪一个包含特定的值。它应该是这样的:
输入:

Madagascar

:

The countries in the same continent are: Morocco, Ghana, Madagascar

我怎么能得到这个结果与Javascript?

您可以这样做;

function getContinentNeighbours(country){
  return country +
         " is in the same continent with: " +
         continents.reduce((p,continent) => continent.includes(country) ? p += continent.filter(f => f !== country)
                                                                                        .reduce((f,s) => f + ", " + s)
                                                                        : p ,"");
}
var northamerica = ["USA","Canada","Mexico"],
          europe = ["France", "Germany", "Italy"],
          africa = ["Morocco", "Ghana", "Madagascar"],
      continents = [northamerica, europe, africa];
console.log(getContinentNeighbours("Mexico"));

您要找的是Array.prototype.includes

europe.includes("Madagascar") // false
northamerica.includes("Madagascar") // false
africa.includes("Madagascar") // true

或者您可以使用Array.prototype.indexOf -如果该元素不在数组中,则返回-1。

相关文章: