整体思路
/**
* 迭代实现
*/
function demo1 () {
// 前置代码
for (初始代码; 循环条件; 迭代代码) {
// 循环体
}
// 后置代码
}
/**
* 递归实现
*/
function demo2 () {
// 前置代码
初始代码;
_demo2(){
if (!循环条件) return
// 循环体
迭代代码;
_demo2()
}
_demo2()
// 后置代码
}
1、数组求和
let arr = [1, 2, 3, 4]
function sum1 (arr) {
let sum = 0
for (let i = 0; i < arr.length; i++) {
sum += arr[i]
}
return sum
}
console.log(sum1(arr))
// 递归
function sum2 (arr) {
let sum = 0
let i = 0
function sum2 () {
if (!(i < arr.length)) return
sum += arr[i]
i++
sum2()
}
sum2()
return sum
}
console.log(sum2(arr))
2、数组扁平化
let arr = [1, [1, 2]]
function flatten (arr) {
let stack = [...arr]
let res = []
while (stack.length) {
const node = stack.pop()
if (Array.isArray(node)) {
stack.push(...node)
} else {
res = [...res, node]
}
}
return res
}
console.log(flatten(arr))
function flatten2 (arr) {
let stack = [...arr]
let res = []
function _flatten () {
if (!stack.length) return
const node = stack.pop()
if (Array.isArray(node)) {
stack.push(...node)
} else {
res = [...res, node]
}
_flatten()
}
_flatten()
return res
}
console.log(flatten2(arr))
3、树转数组
let tree = [
{
id: "1",
pid: "-1",
children: [
{
id: "2",
pid: "1",
}
]
}
]
function treeToArray (tree) {
let res = []
let stack = [...tree]
function _treeToArray () {
if (!stack.length) return
const node = stack.pop()
const { children, ...rest } = node
res.push(rest)
if (node.children) {
stack.push(...children)
_treeToArray()
}
}
_treeToArray()
return res
}
console.log(treeToArray(tree))
function treeToArray2 (tree) {
let res = []
let stack = [...tree]
while (stack.length) {
const node = stack.pop()
const { children, ...rest } = node
res.push(rest)
if (node.children) {
stack.push(...children)
}
}
return res
}
console.log(treeToArray2(tree))
3、数组转树
let arr = [{ id: '1', pid: '-1' }, { id: '2', pid: '1' }]
function arrayToTree (arr) {
let map = arr.reduce((acc, cur) => {
acc[cur.id] = cur
return acc
}, {})
arr.forEach(ele => {
if (map[ele.pid]) {
map[ele.pid].children = map[ele.pid].children || []
map[ele.pid].children.push(ele)
delete map[ele.id]
}
})
return Object.values(map)
}
console.log(JSON.stringify(arrayToTree(arr)))
function arrayToTree2 (arr) {
let map = arr.reduce((acc, cur) => {
acc[cur.id] = cur
return acc
}, {})
function _arrayToTree (i) {
if (i >= arr.length) return
const ele = arr[i]
if (map[ele.pid]) {
map[ele.pid].children = map[ele.pid].children || []
map[ele.pid].children.push(ele)
delete map[ele.id]
}
_arrayToTree(++i)
}
_arrayToTree(0)
return Object.values(map)
}
console.log(JSON.stringify(arrayToTree2(arr)))
参考链接:发现更多精彩视频 - 抖音搜索