javascript 嵌套的 foreach 循环和这个

javascript nested foreach loops and this

我有嵌套的 foreach 循环,我想访问子项中父项的索引。通常我会知道如何做到这一点,但我已经抽象*回调函数,所以我可以在我的程序的其他部分使用它们。 我认为这与 this 有关,但我无法弄清楚。

*这里的正确词是什么?

下面的代码是我试过的

const processChildArray = function( value, index ){
    console.log( `${this.index} ${index} ${value}` );
}

const processParentArray = function( value, index ){
    value.childArray.forEach( processChildArray, this )
}

parentArray.forEach( processParentArray );

但它说索引未定义

this processChildArray 不是您想要的

一种解决方案是将外部索引绑定到 processChildArray 调用

const processChildArray = function( pIndex, value, index ){
    console.log( `${pIndex} ${index} ${value}` );
}

const processParentArray = function( value, index ){
    value.childArray.forEach( processChildArray.bind(null, index) )
}

const parentArray = [{childArray:[1,2]},{childArray:[3,4]}];
parentArray.forEach( processParentArray );

请注意,当像这样绑定一个函数时,绑定的参数将是第一个,然后是来自 forEach 回调的参数

我不知道你的数据,但我认为这可能会有所帮助

parentArray.forEach(function(entry) {
  entry.childArray.forEach(function(childrenEntry, index) {
    console.log(`${entry.index} ${index} ${childrenEntry}`);
  });
});

这可以通过 2 个嵌套的 forEach 循环来实现。

例如:

var parent = [1,2,3,4];
var child = ['a','b','c','d'];
parent.forEach((parentItem, parentValue) => {
    child.forEach((childItem, childValue) => {
        console.log(parentItem + ' ' + parentValue + ' ' + childItem + ' ' + childValue )
    });
});

和平!