How does JavaScript generate a simple arithmetic sequence? This article will share with you how to use for loop to implement js to generate a simple arithmetic sequence. Please refer to this article for specific implementation methods.
The question is very simple, the easiest way is to use a for loop
let arr = [] for (let i = 0; i < b - a + 1; i++) { arr.push(i + a) } return arr
Advanced
When I think about it later, I feel that the previous method is a bit stupid , and then came up with these methods
Array gaps
join() and toString() will treat gaps as undefined (string form):
// 拼接 > 分割 > map Array(b - a + 1).join(' ').split(' ').map((e, i) => a + i) // 转字符串 > 分割 > map Array(b - a + 1).toString().split(',').map((e, i) => a + i)
Use the Array.from method to achieve:
// 空数组转真数组 Array.from(Array(b - a + 1)).map((e, i) => a + i) // 类似数组的对象转数组 Array.from({ length: b - a + 1 }).map((e, i) => a + i) Array.from({ length: b - a + 1 }, (e, i) => a + i)
The expansion operator of ES6 can also help us accomplish this more conveniently
[...Array(b - a + 1)].map((e, i) => a + i) fill()、entries()、keys()方法也不会忽略空位 Array(b - a + 1).fill(' ').map((e, i) => a + i) [...Array(b - a + 1).entries()].map(e => e[0] + a) [...Array(b - a + 1).keys()].map(e => e + a)
There are other ways to accomplish this , such as findIndex(), find(), for...of, etc. These methods are not simple enough to implement, so there is no need to go into details.
Related recommendations:
Common JavaScript memory leaks
Ten concepts that JavaScript developers should know
Introduction to the use of split function in JavaScript from shallow to deep
The above is the detailed content of JavaScript generates simple arithmetic sequence. For more information, please follow other related articles on the PHP Chinese website!