尝试循环条件为什么我变得不确定

时间:2019-01-30 04:45:46

标签: javascript json

我对自己的代码有疑问。 我的代码如下:

var data = {"Q1":"Male","Q5":"USA"};

var combine = [	{"Q1":"Male","Q5":"USA"},
        {"Q1":"Male","Q5":"Japan"}];

for(key in combine[0]){

   if(key.length > 1){
    var num = key.length;
    console.log(key, data.key);		
    }
}

我的目的是尝试使用data.key返回data.Q1和data.Q2,但是当我console.log(key, data.key);

键是Q1,Q5,但是data.key是未定义的,我认为它必须是“ Male”和“ USA”

enter image description here

5 个答案:

答案 0 :(得分:2)

console.log(key, data.key);更改为console.log(key, data[key]);

var data = {"Q1":"Male","Q5":"USA"};

var combine = [ {"Q1":"Male","Q5":"USA"},
                {"Q1":"Male","Q5":"Japan"}];

for(key in combine[0]){
        if(key.length > 1){
        var num = key.length;
        console.log(key, data[key]);     
        }
    }

答案 1 :(得分:1)

由于key是动态的,因此请使用[]括号表示法来访问属性。这将使您可以动态评估key

 var data = {"Q1":"Male","Q5":"USA"};

var combine = [ {"Q1":"Male","Q5":"USA"},
                {"Q1":"Male","Q5":"Japan"}];

for(key in combine[0]){
    if(key.length > 1){
    var num = key.length;
    console.log(key, data[key]);     
    }
}

答案 2 :(得分:0)

Combine [0]中的

key表示对象的键名。

因此key.length为您提供密钥的长度,即 Q1的长度

使用data [key]获取整个对象

var data = {
  "Q1": "Male",
  "Q5": "USA"
};

var combine = [{
    "Q1": "Male",
    "Q5": "USA"
  },
  {
    "Q1": "Male",
    "Q5": "Japan"
  }
];

for (key in combine[0]) {
  if (key.length > 1) {
    var num = key.length;
    console.log(key);
    console.log("key's length--", key.length);
    console.log("key's data--", data[key]);
  }
}

答案 3 :(得分:0)

您的data对象是地图。尝试使用data[key]

var data = {"Q1":"Male","Q5":"USA"};
var combine = [ {"Q1":"Male","Q5":"USA"},
                {"Q1":"Male","Q5":"Japan"}];
for(key in combine[0]){
   if(key.length > 1){
        var num = key.length;
        console.log(key, data[key]);     
   }
}

答案 4 :(得分:0)

data.key尝试访问未定义数据对象中的属性key

尝试使用[]括号。

示例:

 var data = {"Q1":"Male","Q5":"USA"};

var combine = [ {"Q1":"Male","Q5":"USA"},
                {"Q1":"Male","Q5":"Japan"}];

for(key in combine[0]){
        if(key.length > 1){
        var num = key.length;
        console.log(key, data[key]);     
        }
    }