Reputation: 13
When i look at others code (because im curious how they do things) i common stumble across a specific var that catches my eye for example:
var data = {
names = 0;
charMove = 0;
hunger = 100;
thirst = 100;
}
I want to understand this for later when it could be useful in some of my code. I have a moderate understanding on javascript code and love to learn as much as i can so if you have anything please do tell!
Upvotes: 0
Views: 76
Reputation: 588
You have to use
var player = {
"level" : 1,
"x" : 0,
"y" : 0,
"score" : 0,
}
The above is what it called Javascript object, a key-value representation...
Upvotes: 0
Reputation: 11
That is an object. There are multiple ways to create objects in JavaScript.
// An object.
var someObject = new Object();
// An object literal (the preferred way of creating objects).
var anotherObject = {};
They’re doing the exact same thing, but object literals are quicker to write. It’s also good to use white-space (tabs, and spaces) for neatness and readability.
Moreover, objects are merely collections of name/value pairs. In example:
var person = {
firstname: 'John',
lastname: 'Doe'
};
'Person' is the object, and it has some properties. 'firstname' and 'lastname' are the keys, while 'John' and 'Doe' are the values. Values can also be other collections of name/value pairs. For example:
var person = {
firstname: 'John',
lastname: 'Doe',
address: {
street: '111 Main St.',
city: 'New York',
state: 'NY'
}
};
A property of an object could be a primitive type (a boolean, string, number, etc.) or it could be another object — a child object so-to-speak. An object, along with its properties, can also contain methods which are nothing more than functions. However, we use the term 'method' when referring to a function that lives within an object.
Example of an object literal containing a method as one of its properties (which is just a function inside an object):
var person = {
firstname: 'John',
lastname: 'Doe'
method: function(parameters) {
// do something;
}
};
Upvotes: 1
Reputation: 163
I dont use javascript but it looks like a type or struct. each member field can be accessed on its own.
The entire struct can be initialised at once such as
var player = {
level = 1,
x = 0,
y = 0,
score = 0
}
then the member felds can be modified individualy, such as
player.score = player.score + 100;
A struct make it much easier to pass multiple data into functions rather than having to pass separate variables.
Upvotes: -2
Reputation: 630
What you are probably talking about are Objects (although they are defined a little bit different).
They basically are just a Map or Dictionary that maps keys to values and are defined as follows:
var obj = {
key: "value",
key2: true,
key3: function() {}
}
Where the right side can be pretty much everything including other objects.
values can be accessed (read and write) by using obj.key
or obj["key"]
You can read up more about them here
Upvotes: 4