You have 2 ways to declare a new object. The first way is to using a shorthand declaration while the second way is to declare a new object in the same way like other programming language.
var o = {};
OR
var o = new Object();
Unlike other strong typed programming language such as C# or C++, Javascript allows you adding new property at anytime.
For example, adding name and age properties to an object instance:
o.name = 'John';
o.age = 18;
o.savings = 2100;
console.log(o);
You are allowed to remove any property as well:
delete o.savings;
console.log(o);
To retrieve all property names from an object, you need to call Object.keys() function which returns an array of string:
var properties = Object.keys(o);
console.log(properties);
Let says, you want to access the property value without knowing the property name:
var age_of_the_person = o[properties[1]];
But, you can't access the property value by index:
var not_working = o[1];
console.log(not_working);
Wednesday, 20 July 2016
Thursday, 14 July 2016
Javascript object is name value collection
In Javascript, an object is a name value collection.
// the shorthand to declare an new object,.
var o = {};
// set the age to 18.
o['age'] = 18;
// you have 2 ways to retrieve the age:
// property style:
console.log(o.age);
// name value collection style:
console.log(o['age']);
// you may also assigning the value with the "name" that can't be access in "property" style.
o['abc-1'] = 1;
o['name 1'] = 2;
console.log(o['abc-1']);
console.log(o['name 1']);
// the shorthand to declare an new object,.
var o = {};
// set the age to 18.
o['age'] = 18;
// you have 2 ways to retrieve the age:
// property style:
console.log(o.age);
// name value collection style:
console.log(o['age']);
// you may also assigning the value with the "name" that can't be access in "property" style.
o['abc-1'] = 1;
o['name 1'] = 2;
console.log(o['abc-1']);
console.log(o['name 1']);
Subscribe to:
Comments (Atom)
We are moving
We are moving this blog to our new blog site: https://ciysys.com/blog/nodejs.htm
-
Overview Usually, we start developing a new system with designing database and then writing codes. If you are not a fan of ORM, you will h...
-
Below is the sample HTML which will hide the URL at the page header when printing with Javascript. <html moznomarginboxes > ...
-
You can draw a simple pie chart & doughnut chart with SVG + CSS. This is quite simple and straight forward. But the limitation is that i...