js树形结构如何从最深层往上匹配

JavaScript07

js树形结构如何从最深层往上匹配,第1张

一、树结构

定义一颗树,JS中常见的树形数据结构如下,children属性对应的是子树

let tree = [

{

id: '1',

name: '节点1',

children: [

{

id: '1-1',

name: '节点1-1'

}

]

},

{

id: '2',

name: '节点2',

children: [

{

id: '2-1',

name: '节点2-1'

},

{

id: '2-2',

name: '节点2-2',

children: [

{

id: '2-2-1',

name: '节点2-2-1'

}

]

}

]

},

{

id: '3',

name: '节点3'

}

]

二、深度优先遍历(DFS)

1、递归实现

function treeIterator(tree, func) {

tree.forEach((node) =>{

func(node)

node.children &&treeIterator(node.children, func)

})

}

实现逻辑简述:定义treeIterator函数,传入tree(树)和func(回调函数)两个参数,遍历tree数组,执行回调函数,如果当前节点存在children,则递归调用。

函数调用验证:调用treeIterator函数,传入上文定义好的树结构数组,打印出每个节点的name值。

treeIterator(tree, (node) =>{

console.log(node.name)

})

控制台打印结果如下:

2、循环实现

function treeIterator(tree, func) {

let node, curTree = [...tree]

while ((node = curTree.shift())) {

func(node)

node.children &&curTree.unshift(...node.children)

}

}

实现逻辑简述:

(1)定义node作为当前节点,curTree为传入的树(不影响原数组tree);

(2)执行while循环,curTree数组第一个元素从其中删除,并返回第一个元素赋值给node;

(3)①执行回调函数;②如果当前节点存在子树,则追加到curTree数组的开头,继续执行循环,直到curTree没有元素为止。

函数调用验证:参考上述递归实现验证,方式和结果一致。

三、广度优先遍历(BFS)

function treeIterator(tree, func) {

let node, curTree = [...tree]

while ((node = curTree.shift())) {

func(node)

node.children &&curTree.push(...node.children)

}

}

实现逻辑简述:和上述深度优先遍历的循环实现差不多。区别在于如果当前节点存在子树,则追加到list数组的末尾。

js数组的长度可以是无限的,只要内存允许的话。数组的初始长度可以设置,如果需要,随后该长度可以自动增长,使用数字串当作数组的索引等价于直接使用数字索引。

例如:

例如数组元素是String,String的长度js本身是没限制的,所以也不会有一个String太长了不能放在数组中的问题。

对于自定义的对象,它的成员的大小也是不会有限制的,对于Number 对象,js可表示的最大数大约是 1.7976931348623157 x 10 (^308)。

扩展资料:

注意事项

1、JavaScript数组的length属性是可变的。

比如:

arr.length=10//增大数组的长度

document.write(arr.length)//数组长度已经变为10

2、数组随元素的增加,长度也会改变。

如下:

arr[15]=34         //增加元素,使用索引为15,赋值为34

alert(arr.length)  //显示数组的长度16

本文实例讲述了JS获取数组最大值、最小值及长度的方法。分享给大家供大家参考,具体如下:

//最小值

Array.prototype.min

=

function()

{

var

min

=

this[0]

var

len

=

this.length

for

(var

i

=

1

i

<

len

i++){

if

(this[i]

<

min){

min

=

this[i]

}

}

return

min

}

//最大值

Array.prototype.max

=

function()

{

var

max

=

this[0]

var

len

=

this.length

for

(var

i

=

1

i

<

len

i++){

if

(this[i]

>

max)

{

max

=

this[i]

}

}

return

max

}

//数组长度

var

array

=

new

array(1,2,3,2,4,55,2)

alert(array.length)//输出7

希望本文所述对大家JavaScript程序设计有所帮助。