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

JS 数组扁平化之简单方法实现 #75

Open
xuya227939 opened this issue Sep 10, 2019 · 0 comments
Open

JS 数组扁平化之简单方法实现 #75

xuya227939 opened this issue Sep 10, 2019 · 0 comments
Labels

Comments

@xuya227939
Copy link
Owner

xuya227939 commented Sep 10, 2019

什么是扁平化

一句话解释,数组扁平化是指将一个多维数组(含嵌套)变为一维数组

扁平化之 ES5

toString

const arr = [1, 2, 3, [4, 5, [6, 7]]];

const flatten = arr.toString().split(',');

console.log(flatten);

优点:简单,方便,对原数据没有影响

缺点:最好数组元素全是数字或字符,不会跳过空位

join

const arr = [1, 2, 3, [4, 5, [6, 7]]];

const flatten = arr.join(',').split(',');

console.log(flatten);

优点和缺点同 toString

扁平化之 ES6

flat

const arr = [1, 2, 3, [4, 5, [6, 7]]];

const flatten = arr.flat(Infinity);

console.log(flatten);

优点:会跳过空位,返回新数组,不会修改原数组。

缺点:无

扩展运算符(...)

const arr = [1, 2, 3, [4, 5]];

console.log([].concat(...arr));

优点:简单,方便

缺点:只能扁平化一层

总结

推荐使用 ES6flat 方法

博客

欢迎关注我的博客

@xuya227939 xuya227939 added the JS label Sep 10, 2019
@xuya227939 xuya227939 changed the title js数组扁平化之简单方法实现 JS数组扁平化之简单方法实现 Mar 9, 2020
@xuya227939 xuya227939 changed the title JS数组扁平化之简单方法实现 JS 数组扁平化之简单方法实现 Feb 19, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant