【问题标题】:How can I remove items ahead of the current index in an array?如何删除数组中当前索引之前的项目?
【发布时间】:2021-05-10 17:36:59
【问题描述】:

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

例如我有这个:

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());

【问题讨论】:

标签: javascript arrays ecmascript-6


【解决方案1】:

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);

【讨论】:

    【解决方案2】:

    使用拼接方法。从零开始,将索引作为第二个参数传递。

    d.splice(0, scenarioIndex);
    

    如果你不想改变现有的数组,那么

    [...d].splice(0, scenarioIndex);
    

    【讨论】:

    • 文字显示slice 代码显示splice - 您是要使用哪个?
    • 很抱歉。我的意思是拼接。
    【解决方案3】:

    看起来您只是想从索引 0 拼接到您的 scenarioIndex

    const d = ["one", "two", "three", "four", "five", "six"];
    const scenarioIndex = Math.floor(Math.random() * 5) + 0;
    
    const solution = () => {
      console.log(scenarioIndex);
      return d.splice(0, scenarioIndex);
    };
    
    console.log(solution());

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-28
      • 2016-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      • 1970-01-01
      相关资源
      最近更新 更多