1 回答

TA貢獻1906條經(jīng)驗 獲得超3個贊
在這里,我為您創(chuàng)建了一個幫助函數(shù),它將動物訂單作為要檢查的字符串,格式為"animal < animal"... 以及要檢查的動物數(shù)組,您可以選擇所需的任何動物數(shù)組,兩個數(shù)組的大小并不重要所有動態(tài),因此它適合很多用途,現(xiàn)在我認為您可以輕松完成其余的工作:)
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"));
添加回答
舉報