Javascript 数组包含/包含子数组

Javascript array contains/includes sub array(Javascript 数组包含/包含子数组)

本文介绍了Javascript 数组包含/包含子数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查一个数组是否包含另一个数组.子数组的顺序很重要,但实际偏移量并不重要.它看起来像这样:

I need to check if an array contains another array. The order of the subarray is important but the actual offset it not important. It looks something like this:

var master = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3]; 

var sub = [777, 22, 22]; 

所以我想知道 master 是否包含 sub 类似的东西:

So I want to know if master contains sub something like:

if(master.arrayContains(sub) > -1){
    //Do awesome stuff
}

那么如何才能以优雅/高效的方式完成呢?

So how can this be done in an elegant/efficient way?

推荐答案

fromIndex 参数

此解决方案的特点是对索引进行封闭,以便在数组中搜索元素的起始位置.如果找到子数组的元素,则搜索下一个元素以递增的索引开始.

This solution features a closure over the index for starting the position for searching the element if the array. If the element of the sub array is found, the search for the next element starts with an incremented index.

function hasSubArray(master, sub) {
    return sub.every((i => v => i = master.indexOf(v, i) + 1)(0));
}

var array = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3];

console.log(hasSubArray(array, [777, 22, 22]));
console.log(hasSubArray(array, [777, 22, 3]));
console.log(hasSubArray(array, [777, 777, 777]));
console.log(hasSubArray(array, [42]));

这篇关于Javascript 数组包含/包含子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Javascript 数组包含/包含子数组

基础教程推荐