如果我有一个列表l1=["A","B","C"]
,并且我有另一个列表l2=["X","Y","Z","A","B","C","1","2","3"]
,我该如何有效地检查l1
中是否还出现了l2
,还有订单。< / p>
在这种情况下,它会显示在列表中,但如果l1
为["A","C","B"]
,则不会。或者,如果它是l2=["X","Y","Z","A","D","B", "C","1","2","3"]
,也应该找不到它,因为它也必须是顺序的。
由于
答案 0 :(得分:1)
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"]));
&#13;
<强>更新强>
这是如何运作的:
l1.join('')
和l2.join('')
将数组转换为字符串 join on MDN
.indexOf
告诉我们l2
indexOf on MDN
l1
字符串的毒药在哪里?
~
技巧是一个Bitwise NOT运算符而没有进入细节,它在Java脚本中将-1
转换为0
并将0
转换为-1
除true
0
!!
(双重否定)将Number
类型转换为Boolean
类型What is the !! (not not) operator in JavaScript?
答案 1 :(得分:1)
如果在第二个数组中找到,可以使用every()
方法并存储第一个元素的索引,然后只增加该索引并检查它是否存在于第二个数组中。
var l1 = ["A", "B", "C"]
var l2 = ["X", "Y", "Z", "A", "B", "C", "1", "2", "3"]
var check = l1.every(function(e, i) {
if (i == 0) {
var start = l2.indexOf(e);
if (start == -1) return false;
else {
this.start = start;
return true;
}
} else {
return e == l2[this.start += 1]
}
}, {});
console.log(check)
&#13;
更新:您还可以使用every()
和some()
。
var l1 = ["A", "B", "C"]
var l2 = ["X", "A", "Z", "A", "B", "C", "1", "2", "3"]
function check(arr1, arr2) {
return arr2.some(function(e, i) {
if (e == arr1[0]) {
return arr1.every((a, j) => a == arr2[i + j])
}
})
}
console.log(check(l1, l2))
&#13;
答案 2 :(得分:0)
我用过它,似乎工作正常。有没有人看到任何问题?
var l1 = ["A", "B", "C"]
var l2 = ["X", "Y", "Z", "a", "B", "C", "1", "2", "3"]
console.log(search(l1,l2,0));
function CIindexOf(lst, val, offset) {
var lVal = val.toLowerCase();
for(var i=offset; i<lst.length; i++) {
if (lst[i].toLowerCase() == lVal) return i;
}
return -1;
}
function search(l1, l2, offset) {
if (l1.length == 0) return 0;
var index = CIindexOf(l2, l1[0], offset);
if (index == -1) return -1;
for (var i=1; i<l1.length; i++) {
if (l1[i].toLowerCase() != l2[index+i].toLowerCase()) return search(l1, l2, index+1);
}
return index;
}
答案 3 :(得分:-1)
此版本具有良好的性能(方法中没有回调),可以处理任何类型的内容。
function isContain(arr1, arr2) {
var arr2Length = arr2.length;
if (arr2Length > arr1.length) return false; // quick check if arr2 is bigger than arr1 is always false
var lastPos = -1;
var i;
while (~(lastPos = arr1.indexOf(arr2[0], lastPos + 1))) {
for (i = 0; i < arr2Length; i++) {
if (arr1[lastPos + i] !== arr2[i]) break;
}
if (i === arr2Length ) return true;
}
return false;
}
console.log(isContain(["X","Y","Z","A","B","C","1","2","3"], ["A","B","C"]));
console.log(isContain(["X","Y","Z","A","D","B", "C","1","2","3"], ["A","B","C"]));
console.log(isContain(["X","Y","Z","A","B","C","1","2","3"], ["AB","C"]));
console.log(isContain(["X","Y","Z","AB","C","1","2","3"], ["AB","C"]));
console.log(isContain([false, false, true, false, false, true], [true, true]));
console.log(isContain([false, false, true, false, false, true], [true, false]));
console.log(isContain([false, false, true, false, false, true], [1, 0]));
console.log(isContain([1, 1], [1, 1, 1]));