深度遍历数组 reduce
function flatten(array) {
return array.reduce(function (arr, item) {
return (item && Object.prototype.toString.call(item) === '[object Array]'
? Array.prototype.push.apply(arr, flatten(item))
: arr.push(item)
, arr);
}, []);
}
flatten([1,2,[3,[4,5],6],7]).length
遍历DOM节点
function flatten(array) {debugger
if (Object.prototype.toString.call(array) === '[object NodeList]') {
array = Array.prototype.slice.call(array)
}
return array.reduce(function(arr, item) {debugger
return (item && item.childNodes && item.childNodes.length ?
Array.prototype.push.apply(arr, flatten(item.childNodes)) :
arr.push(item), arr);
}, []);
}
flatten(document.documentElement.childNodes).length