简体   繁体   English

如何使用循环创建多个对象属性

[英]How to create multiple object properties with a loop

I'm learning JavaScrit/node.JS and I made the code below, which checks for how many vehicles a player has stored in the database once he joins the server and spawns all them.我正在学习 JavaScrit/node.JS 并且我编写了下面的代码,它检查玩家在加入服务器并生成所有车辆后在数据库中存储了多少车辆。 The problem is that it only works for one vehicle right now (personalVehicles gets overwritten, I belive)问题是它现在只适用于一辆车(personalVehicles 被覆盖,我相信)

mp.events.add("playerReady", (player) => {
    pool.getConnection((err, con) => {
        if (err) console.log(err)
        console.log()
            con.query("SELECT vehicleID, vehicleModel, vehicleSpawnX, vehicleSpawnY, vehicleSpawnZ FROM vehicles WHERE vehicleType = ? AND vehicleOwner = ?", ["players", player.playerID], function (err, result) {
                if (err) console.log(err)
                for (i = 0; i < result.length; i++) {
                    vehicleModel = result[i].vehicleModel
                    player.personalVehicles = mp.vehicles.new(parseInt(vehicleModel), new mp.Vector3(result[i].vehicleSpawnX, result[i].vehicleSpawnY, result[i].vehicleSpawnZ))
                }
            });
        con.release()
    });
});

I've tried switching player.personalVehicles with player.personalVehicles.vehicle[i] , player.personalVehicles.vehicle and player.personalVehicles.[i] , but none of them worked.我试过将player.personalVehiclesplayer.personalVehicles.vehicle[i]player.personalVehicles.vehicleplayer.personalVehicles.[i]切换,但它们都player.personalVehicles.[i]

I pretend to do something like this automatically:我假装自动做这样的事情:

player = {
      personalVehicles = {
               vehicle1 = xxxxxxx
               vehicle2 = xxxxxxx
               vehicle3 = xxxxxxx
               and so on
                          }
}

I know it only works for one vehicle because when I try to destroy the player's vehicles once he leaves only one vehicle gets destroy (the last one in the database).我知道它只对一辆车有效,因为当我试图摧毁玩家的车辆时,他只离开一辆车就会被摧毁(数据库中的最后一辆车)。

Thanks.谢谢。

const obj = {};

you cannot do this obj['hits']['hits'] ='whyDosntWork';你不能这样做obj['hits']['hits'] ='whyDosntWork'; due to obj['hist'] does not exists.由于obj['hist']不存在。

You need to do:你需要做:

obj['hits'] = {}

and then obj['hits']['hits'] ='whyDosntWork';然后obj['hits']['hits'] ='whyDosntWork';

And the same for the rest...其余的也一样......

I cannot understand what do you want to do here:我不明白你想在这里做什么:

obj['hits']['hits'][i]['_source.ActiveChannelReleases'][0]['ImageExports'][0]['Resolutions'][0]['Url']

But follow what I said before, you need to create each step the value you want.但是按照我之前说的,你需要为每一步创造你想要的价值。 I can assume that you want an array in ´hits`我可以假设你想要一个 'hits' 数组

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

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