创建一个循环以为javascript中的类添加新的对象实例

如何创建循环以在JavaScript中创建对象/类的新实例?

我试图做一个像这样的循环:

for(i = 0; i < 4; i++){
    var name + i = new Objectname("name1","name2" etc);
}

但这没有用..

我怎样才能做到这一点。

我也想一次在这些对象中添加今天和未来3天的真实日期。 那可能吗?

我现在拥有的代码只是启动一个新实例,在执行新实例之前:

tomorrow.setDate(today.getDate() + 1);

明天明天是const =新的Date(); 所以我认为这也需要循环。

我的课是:

class weatherData {


    constructor(date, minTemp, maxTemp, wind) {
        this.date = date;
        this.minTemp = minTemp;
        this.maxTemp = maxTemp;
        this.wind = wind;
    }

    createRandom(date, averageTemp) {
        const windList = ['ZO', 'ZW', 'NO', 'NW', 'N', 'Z'];
        this.date = date;

        const maxRandom = averageTemp + 2;
        const minRandom = averageTemp - 2;

        this.minTemp = Math.floor(Math.random() * maxRandom) + minRandom;
        this.maxTemp = Math.floor(Math.random() * maxRandom) + this.minTemp;


        const size = windList.length;
        this.wind = windList[Math.floor(size * Math.random())];
    }
}

我在其中创建weatherData的新实例的函数:

function init() {
    // set new dates
    const today = new Date();
    const tomorrow = new Date();
    const nextday = new Date();
    const dayAfter = new Date();


    // create weather for today
    const weer1 = new weatherData(Date.now(), 5, 10, "ZO");
    weer1.createRandom(today, 10);

    // create weather for tomorrow
    tomorrow.setDate(today.getDate() + 1);
    const weer2 = new weatherData(tomorrow, 5, 10, "ZW");
    weer2.createRandom(tomorrow, 10);

    // create weather for next day
    nextday.setDate(today.getDate() + 2);
    const weer3 = new weatherData(nextday, 5, 15, 'ZO');
    weer3.createRandom(nextday, 10);

    // create weather for dayafter
    dayAfter.setDate(today.getDate() + 3);
    const weer4 = new weatherData(dayAfter, 6, 12, 'NO');
    weer4.createRandom(dayAfter, 9);

    let dates = [weer1, weer2, weer3, weer4];

    // loop through the dates to display weather in the table in my html file
    for (let i = 0; i < dates.length; i++) {
        document.getElementById('day' + (i + 1)).innerHTML = dates[i].date.toDateString();
        document.getElementById('n' + (i + 5)).innerHTML = dates[i].maxTemp + '&deg';
        document.getElementById('n' + (i + 1)).innerHTML = dates[i].minTemp + '&deg';
        document.getElementById('w' + (i + 1)).innerHTML = dates[i].wind;


    }
}

init();
评论