对于Var In Loop - 我可以省略它的变量吗?

时间:2013-02-03 17:30:49

标签: javascript

我有以下代码:

function Vanguard(name,grade,skill,power,shield,critical, type, nation, clan, race, imageURL){
    this.name = name;
    this.grade = grade;
    this.skill = skill;
    this.power = power;
    this.shield = shield;
    this.critical = critical;
    this.type = type;
    this.nation = nation;
    this.clan = clan;
    this.race = race;
    this.imageURL = imageURL;
};

var database = {};
database['asura kaiser'] = new Vanguard("Asura Kaiser", 3, "Twin Drive!!", 11000, 0, 1, "Normal Unit", "Star Gate", "Nova Grappler", "Battleroid", "http://images4.wikia.nocookie.net/__cb20120428001646/cardfight/images/thumb/a/a6/VGE_BT01-008EN.jpg/300px-VGE_BT01-008EN.jpg");
database['king of knights, alfred'] = new Vanguard("King of Knights, Alfred", 3, "Twin Drive!!", 10000, 0, 1, "Normal Unit", "United Sanctuary", "Royal Paladin", "Human", "http://images2.wikia.nocookie.net/__cb20121009013434/cardfight/images/thumb/9/95/BT01-001EN_RRR.jpg/300px-BT01-001EN_RRR.jpg");
database['dragonic overlord'] = new Vanguard("Dragonic Overlord", 3, "Twin Drive!!", 11000, 0, 1, "Normal Unit", "Dragon Sanctuary", "Kagerou", "Dragon", "");
database['ceo amaterasu'] = new Vanguard("CEO Amaterasu", 3, "Twin Drive", 10000, 0, 1, "Normal Unit", "United Sanctuary", "Oracle Think Tank", "Human", "");
database['alfred - early'] = new Vanguard("Alfred - Early", 3, "Twin Drive!!", 10000, 0, 1, "Normal Unit", "United Sanctuary", "Royal Paladin", "Human", "");

function printVanguard(p, name){
      for (var p in database[name]){
         document.getElementById('output').innerHTML +=('<b>' + p.charAt(0).toUpperCase() + p.slice(1) + '</b>: ' + database[name][p] + '<br />');
      }
};

在我的printVanguard函数中,有没有一种方法可以使用for var in循环但是打印出除变量imageURL之外的所有东西?现在代码工作,但我想修改它,以便Vanguard对象中的imageURL变量不会打印出来。

(这不是我的完整代码,只是相关内容。如果您需要我的完整代码,请告诉我。)

1 个答案:

答案 0 :(得分:4)

实际上它不是变量,而是属性。您可以通过添加简单条件来阻止输出:

   for (var p in database[name])
       if (p !== "imageURL")
           document.getElementById('output').innerHTML +=('<b>' + p.charAt(0).toUpperCase() + p.slice(1) + '</b>: ' + database[name][p] + '<br />');

如果要向Vanguard添加原型方法,您也可以考虑使用hasOwnProperty来省略继承的属性。但是,为了在生产中使用此代码,您希望不会仅枚举整个对象,而是显式选择属性或使用仅包含数据的嵌套对象。

或者你可以通过使它不可枚举来跳过属性。但是,this是ES 5的一项功能,在旧版浏览器中不起作用:

this.imageURL = imageURL;
Object.defineProperty(this, "imageURL", {enumerable: false});