我是 JavaScript 的新手,我需要检索以这种方式存储在全局定义对象中的信息。
var customMap ={
totalValues:{
total:10000
}
carPrices:{
'CAR1':{date1:price1}
'CAR2':{date2:price2}
}
}
它是使用函数输入的,当我启动 console.log(customMap)
时,我可以完美地看到它的整个结构。问题是当我尝试检索特定信息时。
我总是不确定。
我试过:
for (var i in customMap.totalValues){
console.log(i);
console.log(customMap.totalValues[i]);
}//It doesn't write anything in the log.
console.log(customMap.totalValues["total"]);//undefined
console.log(customMap.totalValues.total);//undefined
我实现的是当我以这种方式查询它时:
console.log(customMap.totalValues);
//{}
//total: 10000
console.log(Object.values(customMap.totalValues));
console.log(Object.keys(customMap.totalValues));
console.log(Object.entries(customMap.totalValues));
都给出相同的返回信息:
//[]
//length: 0
carPrices
对象也是如此。我无法检索每辆车的信息。我是说 CAR1、CAR2...
我已经没有想法了。我不知道是不是因为访问对象的方式不正确,或者对象没有正确定义或者只是因为全局声明。
如果您有任何想法,我将不胜感激。
@ Kirill Matrosov 我在代码下方添加以表达我的意图。正如您可能注意到的那样,对象结构比前一个更大,因为我试图在这个问题上更精确。不管怎样,我发现 JS 不是顺序的,回调对我一点帮助也没有:S
var customMap =
{
totalValues:{},
carPrices:{}
}
function addValuesToCustomMap(date,car,value){
if (!customMap.carPrices[car]){
customMap.carPrices[car] = {
dates: {},
carTotalValue:0,
carPercent:0
};
}
if (!customMap.carPrices[car].dates[date]){
customMap.carPrices[car].dates[date] = value;
}
else if (customMap.carPrices[car].dates[date]){
var auxValue = customMap.carPrices[car].dates[date];
customMap.carPrices[car].dates[date] = auxValue + value;
}
var totalValue_byCar = customMap.carPrices[car].catTotalValue;
customMap.carPrices[car].catTotalValue = totalValue_byCar + value;
if(!customMap.totalValues["total"]){
customMap.totalValues["total"]=value;
}
else{
var tot = customMap.totalValues["total"];
customMap.totalValues["total"]=tot+value;
}
}
function calculatePercentagesByCar(){
var tot = customMap.totalValues["total"];
for (var k in Object.keys(customMap.carPrices)){
var totalCarPrice = customMap.carPrices[k].carTotalValue;
var percent = totalCarPrice*100/tot;
customMap.carPrices[k].carPercent = percent;
}
}
/*
customMap={
totalValue:{
total: xxxxxx
}
carPrices:{
'CAR 1': {
dates:{
{date1:value1},
(...)
{dateN:valueN}
}
carTotalValue: yyyyyy,
carPercent: zzzz
}
(...)
'CAR N': {(...)}
}
}
*/
最佳答案
var customMap ={
totalValues:{
total:10000
},
carPrices:{
'CAR1':{date1:'price1'},
'CAR2':{date2:'price2'}
}
};
console.log(customMap.totalValues.total);
console.log(customMap.carPrices.CAR1);
console.log(customMap.carPrices.CAR2);
关于javascript - 给出未定义结果的对象内部对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52570657/