如果下面有可能,我会徘徊:
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”进行比较。
答案 0 :(得分:1)
如果要通过迭代获取name
属性,则必须检查迭代的属性名称是否为group3
。一旦确定拥有group3
属性,就可以访问name属性。 for...in
循环将迭代对象的每个属性,当使用in layers
时,它会遍历所有layers
属性,因为group3
是layers
上的属性只需遍历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