+ 1
How do you know when to use Square Brackets or dot notation?
4 Respostas
+ 1
I have run into the situation where lets say you have an array(or hash table) and you want to return the Xth item in the array.
This won't work:
var X = 3;
return ary.X;
But this will work:
return ary[X];
0
Consider the below example.
var obj = {};
obj.name = 'VenomVendor';
obj['web site'] = 'VenomVendor.com'; // see space in key
var x = 'runtime';
obj.x = 'X';
obj[x] = 'runtime';
0
You have a misconception: Array is not the same like an object.
An array represents a list and an object represents a single thing.
Arrays always require array[indexNumber] to access elements. Reason being that js will not accept keys starting with a number.
The dot syntax to access an element only works on actual objects where the keys can start with some valid sign or letter.
The only occurence where you have an array and a dot is when you use a property or a method of an array like array.length.
Now to be complete. An array is an object too which is why there is a property array.length.
To make it easy to understand: An array is a special object which only purpous is to manage a list of the same content easily.
- 1
There is not a time when you should or shouldn't use it. It is very much preference. However, you should be consistent in whichever you choose.