//声明的数组
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";
}
但在以下情况下,您必须小心:
- 数组具有不同的长度
- 普通动物不在同一索引中
要正确解决此问题,请使用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";