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 JS函数,用于检查索引位置的动态数量,并在满足条件时返回数组元素_Javascript_Arrays_Array Indexing - Fatal编程技术网

Javascript JS函数,用于检查索引位置的动态数量,并在满足条件时返回数组元素

Javascript JS函数,用于检查索引位置的动态数量,并在满足条件时返回数组元素,javascript,arrays,array-indexing,Javascript,Arrays,Array Indexing,我一直在寻找一种基于动态数返回数组中元素的方法。此动态数将是每个数组元素所需的索引位置数,如果每个元素都可以满足所需的索引位置数(其自身的位置计入需求),则应返回该元素 常数arr=[1,2,3,4,5,6] const requiredIndex=3 因此,对于上面列出的变量,我应该返回[1,2,3,4],因为5和6将无法返回三个索引位置。Array.prototype.slice可能会给您一些帮助。请参阅 const arr=[1,2,3,4,5,6] const requiredInde

我一直在寻找一种基于动态数返回数组中元素的方法。此动态数将是每个数组元素所需的索引位置数,如果每个元素都可以满足所需的索引位置数(其自身的位置计入需求),则应返回该元素

常数arr=[1,2,3,4,5,6]

const requiredIndex=3


因此,对于上面列出的变量,我应该返回[1,2,3,4],因为5和6将无法返回三个索引位置。
Array.prototype.slice
可能会给您一些帮助。请参阅

const arr=[1,2,3,4,5,6]
const requiredIndex=3

console.log(arr.slice(0,arr.length-requiredIndexes+1))
我不是专家,但我认为您可能希望迭代到该位置。你的动态数是随机数吗?您可能还希望克隆阵列并将克隆用作工作阵列。不确定要对数组执行什么操作,但可以从数组中进行切片,并且父数组保持不受影响

function pickposition() {
        var randIndex = Math.floor(Math.random() * clone.length);  
        rand = clone[randIndex];
    clone.splice(randIndex,1);
                         }

看起来您正在查找
arr.slice(0,arr.length-requiredIndexes+1)
?我不明白您的问题。是否要求数组中的所有元素后面至少有n个元素?如果是这样,您可以简单地使用
arr.splice(-(n-1),999)
这非常有效。非常感谢你!