Home > Article > Web Front-end > Detailed code explanation of how javascript traverses the attribute values of an object
Regarding the need for "traversing the properties and values of objects in js". The reason is to make a js plug-in that partially refreshes the table content.
Problem: Failed to obtain the attribute value of the object by traversing the attribute name array
The initial error code is as follows:
for(var i=0;i<dataList.length;i++) { var dataLine="<tr>"; for(var j=0;j<filedList.length;j++){ dataLine+="<td>"+dataList[i].filedList[j]+"</td>"; } dataLine+="</tr>"; $("#"+tableName).append(dataLine); }
First of all, dataList contains an array of objects; filedList contains an array of attribute field names of objects. At first, I thought like this, traverse the dataList, and get an object every time, then nest a for loop, traverse the filedList, get one of its attribute values each time, and then piece it together into a table.
For example: dataList[0] is an Emp object, and Emp has attributes such as id and name. Normally we can get the id value of the current Emp object through dataList[0].id. But if you traverse the attribute field array, you cannot use dataList[0].filedList[0] in this way. This does not mean that the value is not obtained in filedList[0], because I have already obtained the id value of 1 through alert(filedList[0]). So why does the acquisition fail? Because it is looking for a property called filedList[0] in the Emp object! Of course there is no such attribute in the Emp object, so the acquisition fails as it should. So how do we obtain the attribute value of the object?
Solution: Use "enhanced for loop" to traverse
The correct code is as follows:
for(var i=0;i<dataList.length;i++) { var dataLine="<tr>"; for(var filedName in dataList[i]){ dataLine+="<td>"+dataList[i][filedName]+"</td>"; } dataLine+="</tr>"; $("#"+tableName).append(dataLine); }
Solution: Since dataList[i] is an object, so I can get the attribute name of this object every time, and then get the attribute value of this attribute through dataList[i][filedName], that is, object [attribute name].
function displayProp(obj){ var names=""; for(var name in obj){ names+=name+": "+obj[name]+", "; } alert(names); }
The above is the detailed content of Detailed code explanation of how javascript traverses the attribute values of an object. For more information, please follow other related articles on the PHP Chinese website!