简体   繁体   English

Javascript中的变量“变量” - 未定义

[英]Variable “Variables” in Javascript - Undefined

JSON: JSON:

var promiseObj = {
"physical": [],
"virtual": []
}
var config = {
"Environments": [
"LH5",
"LH8",
"AMS"
],
 "Clusters": {
    "LH5": 4,
    "LH8": 4,
    "AMS": 4
}
};

So I am trying to set different promise objects based on the environments and the clusters in the given JSON object above. 所以我试图根据上面给定JSON对象中的环境和集群设置不同的promise对象。

for (var i = 0; i < config.Environments.length; i++) { 
    promiseObj.physical[config.Environments[i]][config.Clusters[config.Environments[i]]] = $http.get('URL').success(function(data) {
    //Successful stuff here 
});

}

However when performing this for loop I get the following error: 但是,当执行此循环时,我收到以下错误:

promiseObj.physical[config.Environments[i]] is undefined

Could someone shed some light into why this is returning undefined, when the object is clearly defined at the start of the document? 当文档的开头明确定义了对象时,有人可以解释为什么返回未定义的原因吗?

You're declaring physical as an array and then accessing it as an object, so you're trying to access a property that can't exist. 您将physical声明为数组,然后将其作为对象进行访问,因此您尝试访问不存在的属性。 Try declaring physical as follows: 尝试声明physical如下:

"physical": {}

Since physical is an empty array, any and all keys within it are undefined . 由于physical是一个空数组,因此其中的任何和所有键都是undefined You need to prime them the first time you use them: 您需要在第一次使用它们时填充它们:

if (typeof promiseObj.physical[config.Environments[i]] == 'undefined') {
    promiseObj.physical[config.Environments[i]] = {};  // or [], whichever you want
}
promiseObj.physical[config.Environments[i]][config.Clusters[config.Environments[i]]] = ...

This is because promiseObj.physical[] is an empty array, you have to initialize the index you want before: 这是因为promiseObj.physical[]是一个空数组,你必须在之前初始化你想要的索引:

for (var i = 0; i < config.Environments.length; i++) { 
    if(!promiseObj.physical[config.Environments[i]]) promiseObj.physical[config.Environments[i]] = {}; // Initialize it
    promiseObj.physical[config.Environments[i]][config.Clusters[config.Environments[i]]] = $http.get('URL').success(function(data) {
    //Successful stuff here 
    });

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM