Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/453.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 一个函数,它接受一个跳过模式,该模式将接受一个数组并返回新的arr_Javascript_Arrays - Fatal编程技术网

Javascript 一个函数,它接受一个跳过模式,该模式将接受一个数组并返回新的arr

Javascript 一个函数,它接受一个跳过模式,该模式将接受一个数组并返回新的arr,javascript,arrays,Javascript,Arrays,我需要创建某种类型的跳过模式,将其设置到一个数组中,该数组能够选择数组中的哪个项将是该跳过模式的第一项,然后返回该模式选择的项 例如,我需要在这个arr=[1,2,3,4,5,6,7,8,9]中跳转2,所以如果它是第二项2,它将返回[2,4,6,7,9],有人知道JS中有什么方法可以做到这一点吗???数组通常是零索引的,所以说开始索引是2对应于数组中的第二个元素有点奇怪,但是像这样的事情应该让你开始 function skip (start, pattern, arr) { let id

我需要创建某种类型的跳过模式,将其设置到一个数组中,该数组能够选择数组中的哪个项将是该跳过模式的第一项,然后返回该模式选择的项


例如,我需要在这个arr=[1,2,3,4,5,6,7,8,9]中跳转2,所以如果它是第二项2,它将返回[2,4,6,7,9],有人知道JS中有什么方法可以做到这一点吗???

数组通常是零索引的,所以说开始索引是2对应于数组中的第二个元素有点奇怪,但是像这样的事情应该让你开始

function skip (start, pattern, arr)
{
    let idx = 0,
    res = [ ];

    pattern.unshift (start == 0 ? start : start - 1); // A bit odd but to accomodate the 1st index in the array being called the second element. You can just make this pattern.unshift (start); if you want to do it normally :)

    for (let i of pattern) {
        idx += i;
        res.push (arr [idx]);
    }

    return res;
}
将提供:

=> skip (2, [ 2, 2, 1, 2 ], [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]);
[ 2, 4, 6, 7, 9 ]
试试看


你能提供更多的例子吗?到目前为止你尝试了什么,你能给我们展示你的代码吗?请阅读
var original = [1,2,3,4,5,6,7,8,9];
var pattern = [2,2,1,2];

console.log(cutArray(original, pattern));

function cutArray(originalArray, jumpPatternArray){
    for(var i = 0; jumpPatternArray.length > i; i++)
        originalArray.splice(i, jumpPatternArray[i] - 1);    
    return originalArray;
}