【问题标题】:Javascript Class Definition with Array Member带有数组成员的 Javascript 类定义
【发布时间】:2017-03-05 10:47:13
【问题描述】:

我用Java写了代码,没问题。这里我给出Java代码:

public class CarGallery {

    static int carCounter=10;
    static Gallery[] car = new Gallery[carCounter]; 

    public static void main(String[] args) {
    car[0].weight = (float) 1.25;
    car[0].weight = (float) 0.87;
    // ... and so on ... // 
    }   
}

 class Gallery {

    public float weight;
    public float height;
    public int colorCode;
    public int stockGallery;
};

问题是,我想用 Javascript 编写相同的代码。这是不起作用的代码:

var cars = {weight:0 , height:0 , stock:0 , model:"..."};
var cars = new Array();

cars[0].weight=1.2;
cars[0].height=0.87;
cars[0].stock=2;
cars[0].model="320";
  • 我阅读了一些文档,发现 Javascript 中没有像 Java 类这样的类定义。
  • 我在 JS 中找到了带有构造函数的类定义,但是 我不想使用构造函数。
  • 该成员应定义为数组,如:

    静态图库[] car = new Gallery[carCounter];

感谢您的帮助!

【问题讨论】:

    标签: javascript java arrays class object


    【解决方案1】:

    JavaScript 相当于你的 Java。

    function Gallery() {
      this.weight = null;
      this.height = null;
      this.colorCode = null;
      this.stockGallery = null;
    };
    
    var carCounter = 10;
    var carGallery = new Array(carCounter);
    
    carGallery[0] = new Gallery();
    carGallery[0].weight = 1.2;
    carGallery[0].height = 0.87;
    carGallery[0].colorCode = 2
    carGallery[0].stockGallery = 3;
    
    carGallery[1] = new Gallery();
    carGallery[1].weight = 2.2;
    ...
    

    【讨论】:

    • 谢谢 jordanwillis,它可以正常工作! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    • 2017-10-20
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多