gpt4 book ai didi

javascript - 如何检查一个列表是否是另一个有顺序的列表的子列表?

转载 作者:行者123 更新时间:2023-11-30 20:58:22 25 4
gpt4 key购买 nike

如果我有一个列表 l1=["A","B","C"],并且我有另一个列表 l2=["X","Y", "Z","A","B","C","1","2","3"],如何有效地检查 l1 是否出现在 l2,也有顺序。

在这种情况下它确实出现在列表中,但是如果 l1["A","C","B"],那么它不会.或者如果它是 l2=["X","Y","Z","A","D","B", "C","1","2","3"] 这也不应该被发现,因为它也必须是连续的。

谢谢

最佳答案

function check(l1, l2) {
return !!~l2.join('').indexOf(l1.join(''))
}
console.log(check(["A","B","C"], ["X","Y","Z","A","B","C","1","2","3"]));
console.log(check(["A","B","C"], ["X","Y","Z","A","D","B", "C","1","2","3"]));

更新

这是它是如何工作的:

l1.join('')l2.join('')array 转换为 string join on MDN

.indexOf 部分告诉我们 l1 中的 l2 字符串的毒在哪里 indexOf on MDN

~ trick 是位非运算符,不用多说,就是将-1 转换为00-1 在 Java 脚本中每个数字都是 true 除了 0

!!(双重否定)是将Number类型转换为Boolean类型What is the !! (not not) operator in JavaScript?

关于javascript - 如何检查一个列表是否是另一个有顺序的列表的子列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47402368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com