0

我有以下代码:

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 但打印除变量 imageURL 之外的所有内容?现在代码可以工作,但我希望对其进行修改,以便 Vanguard 对象中的 imageURL 变量不会打印出来。

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

4

1 回答 1

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的 s 添加原型方法,您也可以考虑使用hasOwnPropertyto 省略继承的属性。但是,为了在生产中使用此代码,您希望不会仅枚举整个对象,而是显式选择属性或使用仅包含数据的嵌套对象。

或者,您可以通过使其不可枚举来跳过带有循环的属性。但是,是 ES 5 的特性,在旧版浏览器中无法使用:

this.imageURL = imageURL;
Object.defineProperty(this, "imageURL", {enumerable: false});
于 2013-02-03T17:35:28.573 回答