如何删除数组中当前索引之前的项目?

我正在尝试从另一个数组的当前索引之前的数组中删除项目。

例如我有这个:

const d = ["one", "two", "three", "four", "five", "six"];
const scenarioIndex = 1

const solution = () => {
  return // return the solution here
};

在这种情况下,结果必须是 ["one"]

我总是必须返回当前和以前的项目。

如果const scenarioIndex = 2必须返回["one", "two"]

我尝试了几件事但没有成功,这段代码似乎与我需要的相反 => https://codesandbox.io/s/javascript-forked-gjdoy?file=/index.js:0-263

const d = ["one", "two", "three", "four", "five", "six"];
const scenarioIndex = Math.floor(Math.random() * 5) + 0;

const solution = () => {
  console.log(scenarioIndex);
  return d.splice(scenarioIndex + 1, d.length - scenarioIndex);
};

console.log(solution());

回答

splice 方法会改变原始数组,因此只需返回它:

const d = ["one", "two", "three", "four", "five", "six"];
const scenarioIndex = 1

const solution = (arr, index) => (arr.splice(index), arr);

console.log('Splice solution:', solution(d, scenarioIndex));
console.log('Original array:', d);

如果您不想改变原始数组,请更喜欢使用Array.prototype.slice

const d = ["one", "two", "three", "four", "five", "six"];
const scenarioIndex = 1

const solution = (arr, index) => arr.slice(0, index);

console.log('Slice solution:', solution(d, scenarioIndex));
console.log('Original array:', d);


以上是如何删除数组中当前索引之前的项目?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>