Pink HatP
Reactiflux4y ago
68 replies
Pink Hat

✅ – Pink Hat – 00-54 Feb 15

in this code
this.pattern = [
    {
        method: new Function(`console.log(1)`),
        bulletDelay: 1000    
    } ,{
        method: new Function(`console.log(2)`),
        bulletDelay: 1000
        
    } ,{
        method: new Function(`console.log(3)`),
        bulletDelay: 1000
        
    }  
]

for (this.i in this.pattern) {

    setTimeout(()=>this.pattern[this.i].method(), function (i){
        this.z = 0;
        for (this.j = i-1; this.j >=0; this.j--) {
            try {
            this.z += this.pattern[this.j]?.bulletDelay
            } catch (error) {
                console.error(error)
            } finally {
                continue
            }
        }
        console.log(i)
        return this.z
        
    }(this.i))
    console.log(this.pattern[this.i])
    
}

why does
this.pattern[2]
get printed 3 times?
> 0
> {bulletDelay: 1000, method: ƒ}
> 1
> {bulletDelay: 1000, method: ƒ}
> 2
> {bulletDelay: 1000, method: ƒ}
> undefined
> 3
> 3
> 3

When it should be printing
> 0
> {bulletDelay: 1000, method: ƒ}
> 1
> {bulletDelay: 1000, method: ƒ}
> 2
> {bulletDelay: 1000, method: ƒ}
> undefined
> 1
> 2
> 3
Was this page helpful?