Reputation: 3934
I am using get property value in JavaScript by this way
$(document).ready(function () {
var itemList = [{ id: 1, name: 'shohel' }, { id: 2, name: 'rana' }, { id: 3, name: 'shipon' }];
//step 1 : get property value
for (var i = 0; i < itemList.length; i++) {
var id = itemList[i].id;
}
//step 2 : get property value
for (var i = 0; i < itemList.length; i++) {
var id = itemList[i]['id'];
}
//which is better?
});
I can not understand which is better syntax for get property value in javaScript? Thanks.
Upvotes: 0
Views: 65
Reputation: 4086
Both are correct use.
Roundup:
In my opinion, for this usage the first one is the best one. And the second one should be used when index is a variable (computed before), ex :
var index = 'id';
var id = itemList[i][index];
And in this case, your second solution is the only way of doing it, and by the way the better one
Upvotes: 2