Created
February 17, 2017 00:12
-
-
Save yiyizym/3a362473c2e82d74d94c634e73ff360f to your computer and use it in GitHub Desktop.
flatten array in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var flatten = (function(){ | |
var result = []; | |
var _innerFlatten = function(arr){ | |
if(arr.length === 0){ | |
return []; | |
} | |
arr.forEach(item => { | |
console.log(item) | |
console.log('>>>') | |
if(isArray(item)){ | |
_innerFlatten(item); | |
} | |
else{ | |
result.push(item); | |
} | |
}) | |
return result; | |
} | |
function isArray(obj){ | |
return Object.prototype.toString.call(obj).match(/Array/) != null; | |
} | |
return _innerFlatten; | |
})(); | |
var arr = [1,[2],3,[4,[5]],[6,7,8],9]; | |
console.log(arr); | |
var result = flatten(arr); | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
另一个版本,使用 Array.prototype.reduce ,IE9 支持 :