Javascript的动态对象数组

时间:2022-10-11 22:03:41

This is what i have so far. Basically every time i make a new Item object i need it to create a specific number of another object called Sensor. I've tried a few other methods and none seem to way the work that i need.

这是我目前所拥有的。基本上每次我创建一个新项目对象时,我都需要它来创建一个特定数量的另一个对象,称为Sensor。我尝试过其他一些方法,但似乎没有一种方法能达到我所需要的效果。

function Item (id,number,operator,numOfSensors){
    this.id = id;
    this.number = number;
    this.operator = operator;
    this.numOfSensors = numOfSensors;
    var sensor = new Sensor[numOfSensors];

}

var Sensor = {
    timeStamp:[],

    itemPassed: function(){
        timeStamp.push(Date.now());
    }

}

Thanks so much for any help :) i'm a bit new to js EDIT:

非常感谢您的帮助)我对js编辑有点陌生:

Hey guys! Thanks for the help. Basically my issue is neatly making an array of Objects. In the item object i want to make a [numOfSensors] amount of the Sensor object. I cant seem to find a way to do that. SO i guess my question is how would i go about creating an array of objects with a set number of elements?

嘿,伙计们!谢谢你的帮助。基本上,我的问题是创建一个对象数组。在项目对象中,我想制作一个[numofsensor]数量的传感器对象。我似乎找不到那样做的方法。我想我的问题是,我该如何创建一个对象数组?

1 个解决方案

#1


0  

Not sure when you really want to call itemPassed() and whether this is not rather a function of Item, but here is some code that might get you get started:

不确定什么时候真正想要调用itempched(),以及这是否是项的函数,但是这里有一些代码可以让您开始:

var Item = function (id, number, operator, numOfSensors) {
    this.id = id;
    this.number = number;
    this.operator = operator;
    this.numOfSensors = numOfSensors;
    var sensorArray = [];
    for (var i = 0; i<numOfSensors; i++) {
        sensorArray.push(new Sensor());
    }
}

var Sensor = function() {
    this.timeStamps = [];
}

Sensor.prototype.itemPassed = function(){
    this.timeStamps.push(Date.now());
}

See:

看到的:

#1


0  

Not sure when you really want to call itemPassed() and whether this is not rather a function of Item, but here is some code that might get you get started:

不确定什么时候真正想要调用itempched(),以及这是否是项的函数,但是这里有一些代码可以让您开始:

var Item = function (id, number, operator, numOfSensors) {
    this.id = id;
    this.number = number;
    this.operator = operator;
    this.numOfSensors = numOfSensors;
    var sensorArray = [];
    for (var i = 0; i<numOfSensors; i++) {
        sensorArray.push(new Sensor());
    }
}

var Sensor = function() {
    this.timeStamps = [];
}

Sensor.prototype.itemPassed = function(){
    this.timeStamps.push(Date.now());
}

See:

看到的: