[英]Get Object Property Value in JavaScript
I am using get property value in JavaScript by this way 我通过这种方式在JavaScript中使用get属性值
$(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? 我不明白在javaScript中获取属性值哪种更好的语法? Thanks.
谢谢。
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 :
当index是一个变量(之前计算过)时,应使用第二个变量,例如:
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 在这种情况下,您的第二个解决方案是唯一的方法,而且更好的方法是
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.