Reputation: 806
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.
Upvotes: 0
Views: 1559
Reputation: 1066
Why not just create a loop to do what you need. As long as you have the number:
const number = 5;
const numberArray = [];
for(let i = 1; i <= number; i++){
numberArray.push(i);
}
console.log(numberArray);
Upvotes: 2
Reputation: 16908
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));
Upvotes: 0
Reputation: 1661
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(...)
Upvotes: 3