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

微店: 将二维数组转成一维数组的方法有哪些(一面) #10

Open
FishPlusOrange opened this issue Apr 30, 2019 · 1 comment

Comments

@FishPlusOrange
Copy link
Member

FishPlusOrange commented Apr 30, 2019

To:
@FishPlusOrange

面试公司:
微店

面试环节:
一面

问题:
假设现在有一个二维数组,如果我们要把该二维数组转成一维数组,你能想到的方法有哪些呢

@FishPlusOrange
Copy link
Member Author

答案:

  • flat

这是 ES10 的方法,其默认将二维数组转成一维数组:

[[1, 2], [3, 4]].flat() // [1, 2, 3, 4]

其实,flat() 可以将任意维数组转成一维数组,只需要传入被扁平化的层数,比如将三维数组转成一维数组就是 flat(2)

如果是未知层数,还可以使用参数 Infinity

  • concat + 扩展运算符
[].concat(...[[1, 2], [3, 4]]) // [1, 2, 3, 4]
  • reduce + concat
[[1, 2], [3, 4]].reduce((acc, cur) => acc.concat(cur), []) // [1, 2, 3, 4]
  • toString + split

先使用 toString 把数组转成字符串,再使用 split 把字符串转回数组:

[[1, 2], [3, 4]].toString().split(',').map(item => +item) // [1, 2, 3, 4]

但是,该方法存在局限性,不适用于一些包含相对特殊子元素的数组,比如包含 nullundefined、对象类型等。

解答思路:

这道题问的是关于数组的扁平化,主要还是考察数组相关 API 的使用等。

@acodercc acodercc changed the title To FishPlusOrange: 将二维数组转成一维数组的方法有哪些(微店) 微店: 将二维数组转成一维数组的方法有哪些(一面) May 6, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants