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

2.数组扁平化 #3

Open
conan1992 opened this issue Nov 5, 2019 · 0 comments
Open

2.数组扁平化 #3

conan1992 opened this issue Nov 5, 2019 · 0 comments

Comments

@conan1992
Copy link
Owner

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

1.方法一是利用es6提供的flat方法:

console.log(arr.flat(Infinity));

2.方法二是利用正则的方法把中括号去除:

console.log(JSON.stringify(arr).replace(/[\[\]]/g, "").split(","))//数字类型被转成字符串类型

3.方法三-递归:

let result = []
var fn = function(arr){
	for(var i=0;i<arr.length;i++){
		if(Array.isArray(arr[i])){
			fn(arr[i])
		}else{
			result.push(arr[i])
		}
	}
}
fn(arr)
console.log( result )

4.方法四-扩展运算符:

while(arr.some(Array.isArray)){
	arr=[].concat(...arr)
}
console.log(arr)

5方法五-利用reduce迭代,类似递归方法:

function fn(arr){
	return arr.reduce((acc, cur)=>{
		return acc.concat(Array.isArray(cur)?fn(cur):cur)
	}, [])
}
console.log(fn(arr))
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

1 participant