简体   繁体   English

如何为对象的构造函数添加数组参数,从而为每个对象提供自己的数组?

[英]How is it possible to add an array argument to a constructor for an object, thus to give each object its own array?

Is it possible to have a object constructor where each objects has its own array? 是否可以有一个对象构造函数,其中每个对象都有自己的数组?

I am have trouble figuring out the syntax if so. 如果是这样,我很难弄清楚语法。

Right now I am creating objects and a separate array to co-aside the object(waiters) array. 现在,我正在创建对象和一个单独的数组,以共同放置object(waiters)数组。

function Waiter (name, orders[]) {
    this.name = name;
    this.orders = orders;
}

// Constructor for waiter object
function Waiter (name) {
    this.name = name;
}

// Waiter objects
var waiterOne = new Waiter('Timo');
var waiterTwo = new Waiter('Lucian');
var waiterThree = new Waiter('Arpi');


// Array to store waiter object 
var waiters = [
    waiterOne,
    waiterTwo,
    waiterThree
];

// Count so that the same number of arrays are create as waiters
var countWaiterOrders = waiters.length;

// Creating a order array for each waiter object
for(var i = 0; i <= countWaiterOrders; i++){
    var order = [i];
}

Getting error: 出现错误:

Uncaught SyntaxError: Unexpected token [ 未捕获到的SyntaxError:意外令牌[

Is the error message I get when trying to pass an array to the constructor. 是我在尝试将数组传递给构造函数时收到的错误消息。

The desired result would just be that each Waiter object has its own array for orders. 期望的结果将是每个Waiter对象都有其自己的订单数组。

ex: 例如:

console.log(waiters[0]);

Waiter {name: "Timo", orders: []}

Silly question I was just a bit stuck for a while you assign the value to an empty array not the argument. 愚蠢的问题是,您将值分配给空数组而不是参数时,我只是停留了一段时间。

//Waiter constructor //侍者构造函数

function Waiter (name, order) {
    this.name = name;
    this.order = [];
}

Please correct me if I'm missing something, but it seems that you could just use something like this: 如果我缺少某些内容,请更正我,但似乎您可以使用以下内容:

class Waiter {
      constructor(name) {
        this.name = name
        this.orders = []
      }
    }

What you are doing here is creating a class Waiter to which you pass a name as variable. 您在这里所做的是创建一个类Waiter ,并将name作为变量传递给该类。

You can create a Waiter like so: var waiterOne = new Waiter('Tim') . 您可以像这样创建一个Waitervar waiterOne = new Waiter('Tim')

This would then allow you to use waiterOne.name or waiterOne.orders , as the array of orders is created in the constructor of the class. 然后,这将允许您使用waiterOne.namewaiterOne.orders ,因为在类的构造函数中创建了订单数组。

If you wanted to store all your waiters in the array, the good method may be to create a collection class called Waiters - This could be useful if you wanted to do some operations on the whole collection of your Waiters. 如果要将所有侍者存储在数组中,好的方法可能是创建一个名为Waiters的集合类-如果您想对整个Waiters集合进行某些操作,这可能会很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM