簡體   English   中英

推送到陣列的數據不會保留在陣列中

[英]Data pushed to array does not remain in the array

JS / jQuery有一個奇怪的問題。 當我將數據從while循環推入數組時,數據將成為循環的局部數據。

如果我移動console.log(bxStore);則忽略了我的代碼幾乎無法工作的事實。 進入{ready} {}或while循環下方的任何位置,它將讀取未定義的內容。

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

編輯:似乎不是一個可變范圍的問題伙計們,我的示例確實在函數中顯示了它,但是在外部聲明它時,我遇到了同樣的問題。

我沒有足夠的聲譽來發表評論,因此即使它可能無法完全解決您的問題,我也必須用完整的答案寫出來!

因為您在函數中定義了bxStore,所以它僅在該函數中可用(它的“作用域”在函數內部)。 因此,如果將console.log(bxStore)移到document.ready函數中,則看不到bxStore。

解決當前問題的一種方法是按照stravanato的定義將bxStore定義為全局變量(使用bgRegEx命名),以便document.ready函數可以看到它。 更好的方法是擁有bxcycle功能

return bxStore

...然后您可以將結果記錄在控制台上,例如

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

我看過你的codepen。 正確的代碼如下所示:

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范圍在函數內部,因此在外部不可見。 如果console.log在函數內部,則應回顯某些內容,如果在函數外部,則不應該回顯某些內容。

你應該把var bxStore = new Array(); 功能之外。

您必須創建一個閉包以暴露函數的局部變量,因為您在函數內部聲明了bxStore,因此將在函數執行后將其轉儲。 是的,只是簡單的退貨

return bxStore

或者,您可以創建一個全局變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM