简体   繁体   中英

Data pushed to array does not remain in the array

having a strange issue with JS/jQuery. When I push data from a while loop into an array, the data becomes local to the loop.

ignoring the fact my code barely works, if I move console.log(bxStore); into my document ready {} or anywhere below the while loop, it reads undefined.

var bxRegEx =  new RegExp(/[b][x]\d*[y]\d*[w]\d*[h]\d*/) //identifier 

expression

function bxCycle(){ //cycle html for indbx identifiers
    var cycle = 0
    var bxIdGet = document.getElementsByTagName('div')[cycle].outerHTML

    var bxStore = new Array()
    while (bxRegEx.test(bxIdGet)){
        bxStore.push(bxRegEx.exec(bxIdGet))
        cycle++
        bxIdGet = document.getElementsByTagName('div')[cycle].outerHTML
    console.log(bxStore)
    }
}

$(document).ready(function(){
    bxCycle()

})

https://codepen.io/anon/pen/wrRVKw?editors=1112

edit: doesn't appear to be a variable scope issue guys, my example does show it within the function, but when declaring it outside I get the same issue.

I don't have enough reputation to comment yet, so I have to write this in a full blown answer even though it might not fully solve your problem!

Because you define bxStore in the function, it's only usable within that function (it's "scope" is inside the function). So, if you move console.log(bxStore) into the document.ready function it can't see bxStore.

One way to solve your immediate problem is to define bxStore as a global variable (up with bgRegEx) as stravanato says, so that the document.ready function can see it. An even better way would be to have your bxcycle function

return bxStore

... then you could console log your result on document ready like

$(document).ready(function(){
    console.log(bxCycle())
})

I've looked at your codepen. The correct code goes like this:

function bxCycle(){ //cycle html for indbx identifiers
    var bxRegEx =  /bx\d*y\d*w\d*h\d*/i //identifier expression
    var bxStore = new Array();
    for (i in document.getElementsByTagName('div')) {
        if (bxRegEx.test(i)){
            bxStore.push(bxRegEx.exec(i))
        }
    }
    return bxStore
}

$(document).ready(function(){
    console.log(bxCycle())
})

bxStore scope is inside the function so outside it is not visible. If console.log is inside function it should echo something, if it's outside it should not.

You should put var bxStore = new Array(); outside the function.

You have to create a closure to expose the local variable of a function, because you declare bxStore inside a function, it will be dumped after function get executed. Yes just do a simple return

return bxStore

Or you can create a global variable.

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