number = 5
{[...Array(this.props.pages+1)].map((x, i) =>
<h2 key={i} onClick={()=>this.demoMethod(i+1)} className="tc">{ i+1 }</h2>
)}
//expecting result: [1,2,3,4,5]
How to convert number to array of range of that number.
number = 5
{[...Array(this.props.pages+1)].map((x, i) =>
<h2 key={i} onClick={()=>this.demoMethod(i+1)} className="tc">{ i+1 }</h2>
)}
//expecting result: [1,2,3,4,5]
How to convert number to array of range of that number.
This is what probably you want.
const number = 5;
const result = new Array(number).fill(true).map((e, i) => i+1);
console.log(result); // Consoles [1,2,3,4,5]
In your case you are missing fill part.
Use [...Array(this.props.pages+1)].fill(true).map(...)
Array.from({length: number}, (_, i) => i + 1).Use the Array.prototype.keys function to get the iterator of indexes of the generated array. Using the ... spread operator convert the iterator into an array of numbers till the specified range.
The keys() method returns a new Array Iterator object that contains the keys for each index in the array.
Array.prototype.range = (n) => {
return [...new Array(n+1).keys()].slice(1, n+1);
}
console.log([].range(5));