gpt4 book ai didi

javascript - JS变量范围: pushing into an array in one function and accessing it another function

转载 作者:行者123 更新时间:2023-11-28 00:38:12 25 4
gpt4 key购买 nike

http://jsfiddle.net/ujapned5/

我正在尝试创建一个“初始化程序”函数,用于定义 CSS id 和类名。

function init() {

//our empty array for pushing
var DivNamingPushArray = [];

//object where we define our properties that will be used later
var namingScheme = {
"parentId": {
"firstChild": "blah",
"secondChild": "blahblah",
"thirdChild": "blahblahblah"
}
}

//loop through the namingScheme object and push into array
for (propOne in namingScheme) {
DivNamingPushArray.push(propOne);
for (propTwo in namingScheme[propOne]) {
DivNamingPushArray.push(namingScheme[propOne][propTwo])
}
}
}

function execute() {

//call the "init" function
init();

//this cannot be called
console.log(DivNamingPushArray);

//however, why can this be successfully called?
console.log(propOne);
}

execute();

我真的更喜欢将这些函数分开,而不是将 execute 包含在 init 中。稍后还有其他函数需要调用 DivNamingPushArray 变量。

我正在查看有关变量作用域的 MDN 文档,但没有找到简单的解决方案...

最佳答案

我建议你使用第三个函数来分离你的逻辑

关于propOne,你可以在你的问题中看到我的评论,只需将var放在它的前面即可。

<强> Working example here

execute();

function init(app) {
app.DivNamingPushArray = getNamingArray();
}

function execute() {
var app = {};

//call the "init" function
init(app);

console.log(app.DivNamingPushArray);

}

function getNamingArray() {
//our empty array for pushing
var DivNamingPushArray = [];

//object where we define our properties that will be used later
var namingScheme = {
"parentId": {
"firstChild": "blah",
"secondChild": "blahblah",
"thirdChild": "blahblahblah"
}
}

//loop through the namingScheme object and push into array
for (var propOne in namingScheme) {
DivNamingPushArray.push(propOne);
for (var propTwo in namingScheme[propOne]) {
DivNamingPushArray.push(namingScheme[propOne][propTwo])
}
}

return DivNamingPushArray;
}

关于javascript - JS变量范围: pushing into an array in one function and accessing it another function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28238472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com