Examples of javascript object usage and property manipulation
- 2020-03-30 02:11:24
- OfStack
All variables in JavaScript are objects, with two exceptions: null and undefined.
false.toString(); // 'false'
[1, 2, 3].toString(); // '1,2,3'
function Foo(){}
Foo.bar = 1;
Foo.bar; // 1
A common misconception is that the literal value of a number is not an object. This is because of an error in the JavaScript parser, which tried to resolve the point operator as part of a floating point numeric face value.
2.toString(); //Error: SyntaxError
There are many workarounds for making numeric literals look like objects.
2..toString(); //The second dot can be resolved normally
2 .toString(); //Notice the space before the dot
(2).toString(); //The 2 is calculated first
Object as a data type
JavaScript objects can be used as hash tables to store named keys and values.
Use the literal syntax of the object - {} - to create a simple object. This newly created Object inherits from object.prototype without any custom properties.
var foo = {}; //An empty object
//A new object with a custom property of 'test' with a value of 12
var bar = {test: 12};
To access attributes
There are two ways to access an object's properties, the dot operator or the bracket operator.
var foo = {name: 'kitten'}
foo.name; // kitten
foo['name']; // kitten
var get = 'name';
foo[get]; // kitten
foo.1234; // SyntaxError
foo['1234']; // works
The syntax is equivalent, but the bracket operator is still valid in the following two cases - dynamically setting the property - the property name is not a valid variable name.
Note: in the JSLint syntax detection tool, the dot operator is recommended.
Delete the properties
The only way to delete a property is to use the delete operator; Setting a property to undefined or null does not actually delete the property, it simply removes the association between the property and the value.
14
var obj = {
bar: 1,
foo: 2,
baz: 3
};
obj.bar = undefined;
obj.foo = null;
delete obj.baz;
for(var i in obj) {
if (obj.hasOwnProperty(i)) {
console.log(i, '' + obj[i]);
}
}
The output above has bar undefined and foo null - only baz is actually deleted, so it disappears from the output.
Syntax for attribute names
var test = {
'case': 'I am a keyword so I must be notated as a string',
delete: 'I am a keyword too so me' //Error: SyntaxError
};
The property name of an object can be declared using either a string or an ordinary character. However, the second declaration above throws the SyntaxError error before ECMAScript 5 due to another error design in the JavaScript parser.
The reason for this error is that delete is a keyword in the JavaScript language; So in order to work with a lower version of the JavaScript engine, you have to use string literal declarations.