1 回答

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