1 回答
TA贡献1906条经验 获得超3个赞
在这里,我为您创建了一个帮助函数,它将动物订单作为要检查的字符串,格式为"animal < animal"... 以及要检查的动物数组,您可以选择所需的任何动物数组,两个数组的大小并不重要所有动态,因此它适合很多用途,现在我认为您可以轻松完成其余的工作:)
let animals = ["cat", "tiger", "wolf", "lion", "dog", "elephant", "rat"];
function checkAnimalsOrder(animalsArr, orderStr) {
// store the current index of the orderedAnimals array
let ind = 0;
// make an array from that string format "animal > animal" ...;
let orderedAnimals = orderStr.split(" < ");
// filter the animals array to get only the animal that have the same index
// of the orderedAnimals array element
return animalsArr.filter(function(animal, index) {
if(animalsArr[index] === orderedAnimals[ind]) {
ind++;
return animal;
}
}).join("") === orderedAnimals.join("");
// finally join the two arrays as a string and check for equality
}
// Testing
console.log("checking for 'tiger < lion < rat':");
console.log(checkAnimalsOrder(animals, "tiger < lion < rat"));
console.log("checking for 'tiger < dog < rat':");
console.log(checkAnimalsOrder(animals, "tiger < dog < rat"));
console.log("checking for 'tiger < cat < rat':");
console.log(checkAnimalsOrder(animals, "tiger < cat < rat"));
// On the fly
console.log("checking for 'rat < tiger':");
console.log(checkAnimalsOrder(["rat", "elephant", "tiger"], "rat < tiger"));
添加回答
举报