简体   繁体   中英

Array.push updates itself while using inside map function

Here I have used two new arrays for catching URL and Filename value. When I view it on console I got different values everytime like array got overwritten from previous values, Am I doing anything wrong?

downLoadFilesAsZip = async(item) => {

for (const index in item.docLinks) {
  let urlArr=[];
  let fileNameArr = [];
  const url = item.docLinks[index];
  let linkParts = url.split("?");
  let filename = linkParts[0].substring(linkParts[0].lastIndexOf('/')+1);
  urlArr.push(url);
  fileNameArr.push(filename);  
}
}

downLoadAllAsZip = () => {
  {
    this.state.docGroups.length !== 0 && this.state.docGroups.map((item) => {
      if(item.docLinks !== null && item.docLinks.length > 0){
          return(
            this.downLoadFilesAsZip(item)
          );
      }
    })
  }  
}

Follow the loop. Every time your loop runs you are setting empty arrays.

let urlArr=[];
let fileNameArr = [];

bring that outside of your for loop.

Declaring array outside for loop(after import) helped to update every values, For.tsx file answer was this

type urlArr = any[];
type fileNameArr = any[];
let urlArr=[];
let fileNameArr = [];

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