导航栏: 首页 评论列表

深度遍历数组 reduce

默认分类 2018/11/16 02:35

深度遍历数组 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


>> 留言评论