JavaScript:获取对象属性值

时间:2014-01-23 10:57:21

标签: javascript jquery

如果下面有可能,我会徘徊:

var layers = {};
layers.group3 = new L.MarkerClusterGroup(); //some group of objects 
layers.group3.name = "somestr"; //here i want to give a property name to group3 object. 


function checkLayers(data, t) {

    for (var name in layers) {
         var value = layers[name];
         alert("name: "+name+ " value: "+value);

         if(layers.group3.name == t){
             //do something
         }
    }     
}

如何访问group3的name属性。它不会出现在警报中。我还想将值与参数“t”进行比较。

2 个答案:

答案 0 :(得分:1)

如果要通过迭代获取name属性,则必须检查迭代的属性名称是否为group3。一旦确定拥有group3属性,就可以访问name属性。 for...in循环将迭代对象的每个属性,当使用in layers时,它会遍历所有layers属性,因为group3layers上的属性只需遍历group3.name中的属性即可访问layers属性。

for (var name in layers) {
     if(name == "group3" && layers[name].name = t){
         delete layers[name];
     }
} 

这可以在没有迭代的情况下更简单地完成:

alert(layers.group3.name);

答案 1 :(得分:0)

我修改了你的代码。 它工作正常:

var layers = {};
layers.group3 = {};
layers.group3.name = "somestr"; //here i want to give a property name to group3 object. 


function checkLayers(data, t) {

    for (var name in layers) {
         var value = layers[name];
         console.log("name: ", name , " value: " , value);

         if(layers.group3.name == t){
             console.log(layers.group3.name);
         }
    }     
}
checkLayers('', 'somestr');

控制台中的结果:

name:  group3  value:  Object {name: "somestr"} 
somestr