使用split(数组)检查slug项目路径是否有父项

时间:2017-10-18 01:46:23

标签: javascript arrays ecmascript-6

我试图找出第二个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;

}

0 个答案:

没有答案