Как инициализировать массив объектов внутри другого массива объектов? - PullRequest
0 голосов
/ 12 января 2019

У меня есть вопрос. Как я могу инициализировать мои var ингридиенты = []; внутри объекта "рецепта"? Это сделано как я? Или я должен инициализировать его внутри, а не снаружи?

var receitas = [];
var ingredientes = [];



var ingrediente = {
 constructor: function(aNome, aQuantidade){
 this.nome=aNome;
 this.quantidade=aQuantidade;
 }
};

var receita = {
 constructor: function(aTipo, aNome, aTempo, aCusto, aDificuldade, 
 aDescricao, aIngredientes){
 this.nome=aNome;
 this.tipo=aTipo;
 this.tempo=aTempo;
 this.custo=aCusto;
 this.dificuldade=aDificuldade;
 this.descricao=aDescricao;
 this.ingredientes=aIngredientes;
 }
}

Спасибо за любой ответ!

Ответы [ 2 ]

0 голосов
/ 12 января 2019

Я думаю, что вы на самом деле ищете классы, попробуйте сделать это;

var receitas = [];
var ingredientes = [];

class Receita {
  constructor(aTipo, aNome, aTempo, aCusto, aDificuldade, aDescricao, aIngredientes) {
    this.nome = aNome;
    this.tipo = aTipo;
    this.tempo = aTempo;
    this.custo = aCusto;
    this.dificuldade = aDificuldade;
    this.descricao = aDescricao;
    this.ingredientes = aIngredientes;
  }
}

class Ingrediente {
  constructor(aNome, aQuantidade) {
    this.nome = aNome;
    this.quantidade = aQuantidade;
  }
}

Итак, чтобы добавить ingrediente в массив ingredientes, вы должны сделать что-то вроде этого:

var newReceita = new receita('Bolo', 'Bolo de fubá');
ingredientes = [
  new ingrediente('Farinha', 300),
  new ingrediente('Ovos', 2)
]
receita.ingredientes = ingredientes;
0 голосов
/ 12 января 2019

receita.constructor(...) создаст все свойства в receita.

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...