Javascript 如何删除数组中当前索引前面的项?
我试图从一个数组中删除位于另一个数组当前索引之前的项 例如,我有: 常数d=[1,2,3,4,5,6]; Constant scenarioIndex=1 常量解决方案==>{ return//在此处返回解决方案 }; 在这种情况下,结果必须是[一] 我总是必须返回当前和以前的项目 如果const scenarioIndex=2,它必须返回[1,2] 我尝试了几件事,但都没有成功,而这段代码似乎与我所需要的正好相反=> 常数d=[1,2,3,4,5,6]; const scenarioIndex=Math.floorMath.random*5+0; 常量解决方案==>{ console.logscenarioIndex; 返回d.scenarioIndex+1,d.length-scenarioIndex; };Javascript 如何删除数组中当前索引前面的项?,javascript,arrays,ecmascript-6,Javascript,Arrays,Ecmascript 6,我试图从一个数组中删除位于另一个数组当前索引之前的项 例如,我有: 常数d=[1,2,3,4,5,6]; Constant scenarioIndex=1 常量解决方案==>{ return//在此处返回解决方案 }; 在这种情况下,结果必须是[一] 我总是必须返回当前和以前的项目 如果const scenarioIndex=2,它必须返回[1,2] 我尝试了几件事,但都没有成功,而这段代码似乎与我所需要的正好相反=> 常数d=[1,2,3,4,5,6]; const scenarioInde
console.logsolution 看起来您只是想从索引0拼接到场景索引 常数d=[1,2,3,4,5,6]; const scenarioIndex=Math.floorMath.random*5+0; 常量解决方案==>{ console.logscenarioIndex; 返回d.0,场景索引; };
console.logsolution 拼接方法会对原始数组进行变异,因此只需返回它: 常数d=[1,2,3,4,5,6]; Constant scenarioIndex=1 const solution=arr,index=>arr.index,arr; console.log'Splice solution:',solutiond,scenarioIndex;
log'Original array:',d 使用拼接方法。从零开始,将索引作为第二个参数传递
d.splice(0, scenarioIndex);
如果您不想改变现有的数组,那么
[...d].splice(0, scenarioIndex);
那么从零开始?文字上写着切片代码写着拼接-你想用哪一个?很抱歉。我是说拼接。