Home > Web Front-end > JS Tutorial > How to generate an arithmetic sequence using JavaScript

How to generate an arithmetic sequence using JavaScript

亚连
Release: 2018-06-23 17:48:36
Original
2787 people have browsed it

This article will share with you the use of for loops to implement js to generate simple arithmetic sequences. For specific implementation methods, please refer to this article.

The topic is very simple. The simplest way is to use for loops

let arr = []
for (let i = 0; i < b - a + 1; i++) {
 arr.push(i + a)
}
return arr
Copy after login

Advanced

When I thought about it later, I felt that the previous method was a bit stupid, so I came up with these methods again

Array space

join() and toString() will treat gaps as undefined (string form):

// 拼接 > 分割 > map
Array(b - a + 1).join(&#39; &#39;).split(&#39; &#39;).map((e, i) => a + i)
// 转字符串 > 分割 > map
Array(b - a + 1).toString().split(&#39;,&#39;).map((e, i) => a + i)
Copy after login

Use the Array.from method to implement:

// 空数组转真数组
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)
Copy after login

ES6’s expansion operator also It can help us accomplish this more conveniently

[...Array(b - a + 1)].map((e, i) => a + i)
fill()、entries()、keys()方法也不会忽略空位
Array(b - a + 1).fill(&#39; &#39;).map((e, i) => a + i)
[...Array(b - a + 1).entries()].map(e => e[0] + a)
[...Array(b - a + 1).keys()].map(e => e + a)
Copy after login

There are other ways to accomplish this, such as findIndex(), find(), for...of, etc. These methods can be implemented It's not simple enough, so I won't go into details.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to implement keyword fuzzy query in jq.ajax php mysql

How to control concurrency using async and enterproxy Quantity

Image lazy loading imgLazyLoading.js

How to use jquery.page.js to achieve paging effect

The above is the detailed content of How to generate an arithmetic sequence using JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template