[英]How to convert a number into range of array in javascript
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]
如何將數字轉換為該數字范圍的數組。
為什么不創建一個循環來做您需要的事情。 只要您有電話號碼:
const number = 5; const numberArray = []; for(let i = 1; i <= number; i++){ numberArray.push(i); } console.log(numberArray);
這可能就是您想要的。
const number = 5;
const result = new Array(number).fill(true).map((e, i) => i+1);
console.log(result); // Consoles [1,2,3,4,5]
在您的情況下,您缺少fill
部分。
使用[...Array(this.props.pages+1)].fill(true).map(...)
ES6解決方案:
new Array(5).fill(undefined).map((v,i) => i+1);
使用Array.prototype.keys
函數獲取所生成數組的索引的迭代器。 使用...
spread運算符將迭代器轉換為數字數組,直到指定范圍。
keys()方法返回一個新的Array Iterator對象,該對象包含數組中每個索引的鍵。
Array.prototype.range = (n) => { return [...new Array(n+1).keys()].slice(1, n+1); } console.log([].range(5));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.