Javascript array contains/includes sub array(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 数组包含/包含子数组


基础教程推荐
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01