Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何优雅的生成一个长度为n,值从0递增的数组 #10

Open
Topppy opened this issue Sep 3, 2018 · 0 comments
Open

如何优雅的生成一个长度为n,值从0递增的数组 #10

Topppy opened this issue Sep 3, 2018 · 0 comments

Comments

@Topppy
Copy link
Owner

Topppy commented Sep 3, 2018

如何优雅的生成一个长度为n,值从0递增的数组

最基础的实现是for循环

想了想,怎么都是要遍历一次的,顶多把循环变成递归

后来灵机一动,这个需求其实是想要 数组的value = index
所以试着
Object.keys(new Array(10))
结果出乎预料是个空[]

因此改进一下
Object.keys(new Array(10).fill(1))

但是每个值都是string不是number,再想如果转number就又要遍历一次。。

于是去gooogle了
N-ZOO/everycode#19 (comment)
[...Array(10).keys()]

Array(10).keys() 是个迭代器

js中有三种集合对象: 数组,Map,Set(注意没有对象诶)

其中数组的内建迭代器返回数字的index。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant