繁体   English   中英

数组无缘无故地重新初始化?

[英]Array gets re-initialized for no reason?

请看这段代码:在最后一行,它显示 [] 为什么??

const arrcodces =[1,2,3,4]
const arrOfPWs=[]
const data=[]
const arrOfPWs_2=[]
const base=[
'2','3','4','5','6','7','8','9',
'a','b','c','d','e','f','g','h','i',
'k','m','n','p','q','r','s','t','u',
'v','w','y','z','+','=','*','.','/'
]
//********************************* */ 
for(let i=0;i<arrcodes.length;i++){
let pw=''
        for(let j=0;j<6;j++){
            pw=pw+base[Math.floor(Math.random()*base.length)]
        }
        data.push(pw)
}
for(let i=0;i<arrcodes.length;i++){
    arrOfPWs.push({code:arrcodes[i],password:data[i]})
}
//********************************* */ 
async function loopy(element) {
    const newPW = await bcrypt.hash( element.password, 3)
    arrOfPWs_2.push({code:element.code,password:newPW})
}
function doIt() {
    arrOfPWs.forEach(el =>
        loopy(el)
    )
}
doIt()
//********************************* */ 
    console.log(arrOfPWs_2)//SHOWS [] !!!

我试过了,在底部的 console.log() 中它显示 []................................... ...................................................

  1. 你在没有等待的情况下调用 async function loopy。
  2. doIt 也应该是异步的。
  3. forEach 方法是同步的。 console.log(arrOfPWs_2) 不等待 doIt 结果。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
  async function doIt() {
    for(const el of arrOfPWs){
      await loopy(el);
    }  
  )
...

await doIt();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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