-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
数组forEach与for of(in)的区别
先看下面的例子:实现一个广度遍历的功能,先后打印出 'a-1 b-1 a-2 b-2'。
- for of写法,其背后的原理是:数组modules维护dependencies数据,当遍历到当前item({ dependencies })时,添加dependencies到当前数组的末尾,使得遍历完数组第一层时(i=1),modules数组长度扩充到4,此时,i = 2,3则是第二层的依赖,以此实现广度遍历。
但是forEach的遍历次数是由当前调用forEach的数组初始长度来决定,forEach遍历过程中,array.push动态添加的数据不会遍历
var modules = [
{
dependencies: [
{
a: 'a-1',
dependencies: [
{
a:'a-2'
}
]
}
]
},
{
dependencies: [
{
a: 'b-1',
dependencies: [
{
a:'b-2'
}
]
}
]
},
]
for(let item of modules) {
const {dependencies} = item;
if(dependencies) {
for(const depen in dependencies) {
console.log(dependencies[depen]?.a)
modules.push(dependencies[depen])
}
}
}
var modules = [
{
dependencies: [
{
a: 'a-1',
dependencies: [
{
a:'a-2'
}
]
}
]
},
{
dependencies: [
{
a: 'b-1',
dependencies: [
{
a:'b-2'
}
]
}
]
},
]
modules.forEach(({dependencies}, index) => {
console.log(index)
if(dependencies) {
for(const depen in dependencies) {
console.log(dependencies[depen]?.a)
modules.push(dependencies[depen])
}
}
})
Metadata
Metadata
Assignees
Labels
No labels