按索引调整数组大小

时间:2018-10-02 19:42:27

标签: javascript jquery arrays sorting indexing

我有一个类似于...的数组

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

...,开始索引let start = 2和结束索引let end = 5

我要调整数组的大小,从索引 startIndex 开始,以 endIndex 结尾,如下例:

start = 2;
end = 3;

let result = [2, 3]

start = 2;
end = 2;

let result = [2]

start = 0;
end = 8;

let result = [0, 1, 2, 3, 4, 5, 6, 7, 8]

以下是我到目前为止所掌握的内容。但是显然存在一些问题:

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

let start = 2
let end = 3
array.splice(0, start);
array.splice(end, array.length);

console.log(array)

4 个答案:

答案 0 :(得分:1)

您可以使用Array.slice()来获取一个新数组:

const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

const start = 2
const end = 3

const result = array.slice(start, end + 1);

console.log(result)

如果要直接更改原始数组,可以将其与Array.splice()组合:

const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

const start = 2
const end = 3

array.splice(0, array.length, ...array.slice(start, end + 1));

console.log(array)

答案 1 :(得分:1)

您可以使用import React from "react"; import ReactDOM from "react-dom"; class Toggle extends React.Component { constructor() { super(); this.state = { isToggleOn: true, start: false}; this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState(prevState => ({ isToggleOn: !prevState.isToggleOn })); console.log("Pressed"); } componentDidUpdate() { console.log('Component update'); //Have to do this to avoid potential infinty loop document.getElementById('someId').removeEventListener("click", this.handleClick); document.getElementById('someId').addEventListener("click", this.handleClick); } render() { //Need to update component once, to run componentDidUpdate if(!(this.state.start)){ setTimeout(() => { this.setState({start: true }); }, 1000) } // return ( <div> <x3d width='500px' height='300px'> <scene> <shape id="someId"> <appearance> <material id='color' diffusecolor={this.state.isToggleOn ? '1 0 0' : '0 0 1'}> </material> </appearance> <box></box> </shape> </scene> </x3d> </div> ); } } ReactDOM.render(<Toggle />, document.getElementById('toggle')); 并将Array.slice(start,end)加1,因为您希望它具有包容性。

end

答案 2 :(得分:0)

当您将结果数组(第一次拼接后的数组)与实际数组[有问题的数组]的索引进行拼接时,您将得到该输出 请看下面的代码。运行这段代码,看看您会了解

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

let start = 2
let end = 3

array.splice(0,start);

//After splice this is result array [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] 

console.log(array);

//If you splice again with end=3 index you get the result array as [2, 3, 4]. 
// To get your desired output as array you should work on array after you splice first time

array.splice(2,array.length);

console.log(array);

我希望这可以解释您的代码会发生什么。作为对拼接方法的提醒。  splice()方法可在数组中添加/删除项目,并返回删除的项目。

语法:

array.splice(索引,howmany,item1,.....,itemX)

答案 3 :(得分:0)

您可以使用Array#copyWithin并调整数组的length

var start = 2,
    end = 5,
    array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

array.copyWithin(0, start, end + 1).length = end - start + 1;

console.log(array);