We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
To: @FishPlusOrange
面试公司: 微店
面试环节: 一面
问题: 假设现在有一个二维数组,如果我们要把该二维数组转成一维数组,你能想到的方法有哪些呢
The text was updated successfully, but these errors were encountered:
答案:
flat
这是 ES10 的方法,其默认将二维数组转成一维数组:
[[1, 2], [3, 4]].flat() // [1, 2, 3, 4]
其实,flat() 可以将任意维数组转成一维数组,只需要传入被扁平化的层数,比如将三维数组转成一维数组就是 flat(2)。
flat()
flat(2)
如果是未知层数,还可以使用参数 Infinity。
Infinity
concat
[].concat(...[[1, 2], [3, 4]]) // [1, 2, 3, 4]
reduce
[[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]
但是,该方法存在局限性,不适用于一些包含相对特殊子元素的数组,比如包含 null、undefined、对象类型等。
null
undefined
解答思路:
这道题问的是关于数组的扁平化,主要还是考察数组相关 API 的使用等。
Sorry, something went wrong.
FishPlusOrange
No branches or pull requests
To:
@FishPlusOrange
面试公司:
微店
面试环节:
一面
问题:
假设现在有一个二维数组,如果我们要把该二维数组转成一维数组,你能想到的方法有哪些呢
The text was updated successfully, but these errors were encountered: