Rea*_*ing 0 javascript arrays ecmascript-6
我正在尝试从另一个数组的当前索引之前的数组中删除项目。
例如我有这个:
const d = ["one", "two", "three", "four", "five", "six"];
const scenarioIndex = 1
const solution = () => {
return // return the solution here
};
Run Code Online (Sandbox Code Playgroud)
在这种情况下,结果必须是 ["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());Run Code Online (Sandbox Code Playgroud)
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);Run Code Online (Sandbox Code Playgroud)
如果您不想改变原始数组,请更喜欢使用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);Run Code Online (Sandbox Code Playgroud)