开发者

Dynamic creation of JS object

开发者 https://www.devze.com 2023-03-31 05:10 出处:网络
I\'m rewriting a project with hardcoded values to be flexible and dynamic. However, I keep running into trouble.

I'm rewriting a project with hardcoded values to be flexible and dynamic. However, I keep running into trouble.

I wrote most of my JS code now, but I found a couple of bugs that I can't fix, so I decided to start from scratch. I was now thinking to put my data into an object which keeps track of totals. The project basically lets people order tickets, hotels, etc. per event.

However, this used to be hardcoded, like I said. Now it has to be flexible and I'm not sure if it's possible to dynamically create an object? Here's my problem:

The object I used to use was the following:

var total = {   amount: 0,
            tickets: 0,
            passes: 0,
            fri: 0,
            sat: 0,
            sun: 0,
            freecarpass: 0,
            freepass_fri: 0,
            freepass_sat: 0,
            freepass_sun: 0,
            passes_fri: 0,
            passes_sat: 0,
            passes_sun: 0,
            passes_totalPurchase: 0
        };

As you can see, the days are hardcoded. However, with the new system, every event will have differ开发者_Go百科ent days, so I need to be able to build my object based on that, if that makes sense.

For example, if the event runs from wednesday till saturday, the days in the object would be:

wed: 0, thu: 0, fri: 0, sat: 0 

etc.

I'm not sure how to achieve this, if this is even possible? I can provide more code of the project if needed. Thanks in advance.


You ca still add new properties on the fly:

total.wed = 0;

or

total["wed"] = 0;


While I'm not convinced this is the best way to go about solving your problem, yes you can add or remove properties of an object at whim in Javascript. Essentially JS objects are just key-value pairs of properties. So you could start by having an object that all days will share, something like this:

var total = {  
    amount: 0,
    tickets: 0,
    passes: 0
};

Then you can add a property simply by assigning it a value, such as:

total.sat = 3;
total.sun = 1;

W3Schools has a longer explanation of this here.


Yes, in javascript you can do a lot of stuff with objects.

To add new property to an object just do total["nameofyourday"]=0;

This way if you want to dynamically change the value of "nameofyourday", you can put a variable containing a string between the brackets. Like that:

var day="wed";
total[day]=0;

and it will result in having a total.wed value equal to 0.

To provide a more specific implementation more code would be needed I think.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号