我想只在一个"for"声明中为每个数组设置一个"for"计数器,而不是创建两个"for"声明。我怎样才能实现它?



//声明的数组

const aList3 = ["frog", "hippo", "snake", "owl", "sheep"];
const aList4 = ["eagle", "bee", "crab", "hippo", "iguana"];

//声明函数

function isEqual(animals, animals2) {

//为每个数组声明一个计数器

for (let j = 0, k = 0; j < animals.length, k < animals2.length; j++, k++) {

//声明条件

if (animals[j] === animals2[k]) {
return "You finded this common animals: " + animals[j];
}
}
return "You didn't find any common animal";
}

//调用函数

const sameAnimal3 = isEqual(aList3, aList4);
console.log(sameAnimal3);

有些解决方案是使用相同的for计数器,但对我来说不起作用。无论索引位置或长度如何,我都希望它能工作

for (let i = 0; i < animals.length; i++) {
if (animals[i] === animals2[i]) {
return "You finded this common animals: " + animals[i];
}
return "You didn't find any common animal";
}

这可以通过允许两个阵列使用相同的for计数器来实现:

for (let i = 0; i < animals.length; i++) {
if (animals[i] === animals2[i]) {
return "You finded this common animals: " + animals[i];
}
return "You didn't find any common animal";
}

但在以下情况下,您必须小心:

  1. 数组具有不同的长度
  2. 普通动物不在同一索引中

要正确解决此问题,请使用dictionary跟踪看到的动物:

// Dictionary to keep track of seen animals.
const seen = {}
for (let i = 0; i < animals.length; i++) {
// Check both array's current index if animal is seen already.
if(seen[animals[i]] || seen[animals2[i]]) {
// If seen already, take which animal is found between the two array.
const foundAnimal = seen[animals[i]] ? animals[i] : animals2[i]

return "You finded this common animals: " + foundAnimal;
} else {
// If neither animals are seen before, add to the seen dictionary for future reference.
seen[animals[i]] = true;
seen[animals2[i]] = true;
}
}
// You have not seen any animals twice.
return "You didn't find any common animal";

相关内容

  • 没有找到相关文章

最新更新