0

I was looking though the CivClicker game code and I found that he created variables with little "sub variables" inside it. It doesn't look like an array to me.

An example of the variable initialization:

// Initialise Data
var food = {
    name:'food',
    total:0,
    increment:1,
    specialchance:0.1
},
wood = {
    name:'wood',
    total:0,
    increment:1,
    specialchance:0.1
},
stone = {
    name:'stone',
    total:0,
    increment:1,
    specialchance:0.1
},
skins = {
    name:'skins',
    total:0,
},

He later calls the variables using:

food.total++;

And so on. If anyone has any information on this type of variable then I will be very greatful :)

Shadow The Vaccinated Wizard
  • 62,584
  • 26
  • 129
  • 194
DataMosh
  • 75
  • 1
  • 9

5 Answers5

1

These are JavaScript objects. The { .. } syntax is known as literal notation and is one way of creating an object. The attributes between the braces are properties, or methods if the value is a function.

The objects are created using the shorthand var syntax, which is the same as repeating var:

var a = {}, b = {};
// same as
var a = {};
var b = {};

There are other ways of creating objects and setting properties, such as:

var food  = new Object();
food.total = 0;
food['name'] = 'food';

You can also instantiate a function to create an object, whereby the function acts like a class.

function Food {
    this.total = 0;
    this.name = '';
}

var f = new Food();
f.total = 5;
f.name = 'abc';

MDN Working with objects is a good resource that covers this.

MrCode
  • 59,851
  • 9
  • 76
  • 106
0
console.log(typeof {test: 0});

will give you "object"

DoXicK
  • 4,492
  • 22
  • 21
0

the code you posted show 4 Objects, the property total would be a number in this case.

Pharao2k
  • 655
  • 4
  • 22
0

food here is

{
    name:'food',
    total:0,
    increment:1,
    specialchance:0.1
}

wood is

{
    name:'wood',
    total:0,
    increment:1,
    specialchance:0.1
}

In JavaScript multiple variables can be initialized in this way.

More info here - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#Examples

Edit: The comments in this answer gives some benefits of doing so.

Community
  • 1
  • 1
Alok Swain
  • 6,099
  • 5
  • 34
  • 51
0

These are objects.

In programming you can define your own objects to store information about a particular thing.

ie. if you need to store information about a car using code you might create the following object containing a set of paramaters or variables which describe the car.

car = {
 color = "red",
 type = "sports car"
 wheels = 4
}

The purpose of this is to make organizing information easier, ie you can access the paramaters of the car by using car.color or car.wheels.

You can read more here: http://www.w3schools.com/js/js_objects.asp

JensB
  • 5,994
  • 2
  • 42
  • 78