如何在JS中创建上下文数组

时间:2017-09-13 06:42:51

标签: javascript c#

在c#中,添加新值非常容易且不会造成混淆,例如,这是我通常在c#中执行的操作:

namespace Sup
{

public class Pizza
{
    public List<Pepperoni> PepperoniList { get; set; }
    public List<Cheese> CheeseList { get; set; }
    public List<Crust> CrustList { get; set; }
    public List<Sauce> SauceList { get; set; }
}

public class Pepperoni
{
    public string cost { get; set; }
    public string quantity { get; set; }
}

public class Cheese
{
    public string cost { get; set; }
    public string quantity { get; set; }
}

public class Crust
{
    public string cost { get; set; }
    public string quantity { get; set; }
}

public class Sauce
{
    public string cost { get; set; }
    public string quantity { get; set; }
}


public class Program
{
    static void Main(string[] args)
    {
        Pizza p = new Pizza()
                      {
                          PepperoniList = new List<Pepperoni>(),
                          CheeseList = new List<Cheese>(),
                          CrustList = new List<Crust>(),
                          SauceList = new List<Sauce>()
                      };

        p.PepperoniList.Add(new Pepperoni() {cost = "5.00", quantity = "1"});
        p.CheeseList.Add(new Cheese() {cost = "", quantity = ""});
        p.CrustList.Add(new Crust() {cost = "", quantity = ""});
        p.SauceList.Add(new Sauce() {cost = "", quantity = ""});


Console.WriteLine(p.PepperoniList[0].cost);
    }



}
}

正如您所看到的,当我向我的课程添加新值时,我不会再看看我在做什么,它很容易添加新值并显示它们。

然而,在JS这是另一个故事,这就是我目前在JS工作的内容:

var pepperoni= [];
pepperoni.push([["cost"], ["quantity"]]);

console.log(pepperoni[0][0]);

正如你所看到的,这种添加/显示值的形式看起来并不容易阅读和使用,我需要像c#这样的例子,我该怎么办?

3 个答案:

答案 0 :(得分:2)

您的代码可以直接翻译成JavaScript:

class Pizza {
    constructor(){
        this.pepperoniList = [];
        // add more if you want
    }
}

class Pepperoni {
    constructor(cost, quantity){
        this.cost = cost;
        this.quantity = quantity;
    }
}

var p = new Pizza();
p.pepperoniList.push(new Pepperoni(5, 1));    // add a new Pepperoni object

答案 1 :(得分:1)

在Javascript解决方案中,您要添加一个包含两个数组的数组,而不是一个对象。只需添加一个对象即可获得与C#相同的结果:

var pepperoni = [];
pepperoni.push({ cost: 5.0, quantity: 1 });

console.log(pepperoni[0]); // prints { cost: 5.0, quantity: 1 }

答案 2 :(得分:1)

也许是这样的?

&#13;
&#13;
class Ingredient {
  constructor(cost, quantity) {
    this.cost = cost;
    this.quantity = quantity;
  }
}

class Pepperoni extends Ingredient {

}

class Cheese extends Ingredient {

}

class Crust extends Ingredient {

}

class Sauce extends Ingredient {

}

class Pizza {
  constructor(crust, sauce, cheese, pepperoni) {
    this.crust = crust;
    this.sauce = sauce;
    this.cheese = cheese;
    this.pepperoni = pepperoni;
  }
}

const pizza = new Pizza(new Crust(5, 1), new Sauce(2, 1), new Cheese(3, 1), new Pepperoni(2, 1));
console.log(pizza);
&#13;
&#13;
&#13;