js对象质疑如何使用dotand []

时间:2019-05-21 09:11:40

标签: javascript javascript-objects

  

我对代码//this[key].type =='fish'//有疑问。为什么我不能写this.key.type =='fish'或this [key] [type]   ==“鱼”?如何使用[]和圆点?

var aquarium = {

    Nemo: {
        type: 'fish',
        species: 'clownfish',
        length: 3.7
    },
    Peach: {
        type: 'echinoderm',
        species: 'starfish',
        length: 5.3
    },
    "Dragon Statue": { 
        type: "environment", 
        material: "plastic", 
        moves: false
    },

    addCritter: function(name,type,species,length){

        this[name] = { 
            type: type, 
            species: species, 
            length: length
        };
    }

}


aquarium.countfish = function(){
    var numfish = 0;   
    for(var key in this){
        if(this[key].type =='fish'){
            numfish++;
        }
    }
    return numfish;
}
aquarium.countfish();

0 个答案:

没有答案