简体   繁体   中英

Keep a variable in scope within _.forEach() that is not array being looped over

I have a separate array that occasionally I need to push objects into based on the content of the looped array:

let x: any[];
_.forEach(blocks, (block:any) => {
    // some code that does not matter...
    x.push(block.some.property);
});

The documentation says that Lodash's forEach() only passes in 3 arguments; the value, an index, and a collection (assuming this is the initial array/iterable).

Is there a way to force x into scope within the forEach()? Declaring it var just gets a runtime error when it hits x.push(). I've mostly solved the problem with another approach entirely, but it's irritating that there's no way to insist.

Try initializing the x variable

let x: any[]=[];

Most probably it is throwing this error to you在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM