[英]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.