我试图找出第二个slug是否是第一个的父母:
"questions/ask" and "questions"
我不想使用String.startsWith,因为:
"questions/ask" and "question" must not pass.
*评论中针对此案例的解决方案。
你们可以帮助我为这个功能提供更清洁的解决方案吗? ES6?
const a = ["ask", "questions"];
const c = ["questions", "ask", "anything"];
const b = ["questions"];
console.log(arrayStartsWith(b, a)); //`questions` is not the first element
console.log(arrayStartsWith(b, c)); //`questions` is present in sequence
function arrayStartsWith(needleArray, haystackArray) {
if(haystackArray.length < needleArray.length) {
return false;
}
for(let i = 0; i < needleArray.length; i++) {
if(haystackArray[i] !== needleArray[i]) {
return false;
}
}
return true;
}