JS Example Method for Traversing Object Properties
- 2021-07-10 18:14:03
- OfStack
This article illustrates the method of JS traversing object attributes. Share it for your reference, as follows:
JavaScript traversal of a certain object all the attribute names and values of the method, so when you want to use the method is very intuitive and convenient. The code is as follows:
/*
* Used to traverse all property names and values of the specified object
* obj Objects to traverse
* author: Jet Mah
*/
function allPrpos ( obj ) {
// Used to hold all attribute names and values
var props = "" ;
// Start traversing
for ( var p in obj ){
// Method
if ( typeof ( obj [ p ]) == " function " ){
obj [ p ]() ;
} else {
// p Is the property name, obj[p] Is the value of the corresponding attribute
props += p + " = " + obj [ p ] + " \t " ;
}
}
// Finally, all properties are displayed
alert ( props ) ;
}
The reflection mechanism of AJAX and JavaScript, which means that the program can obtain its own information at runtime. For example, an object can know what methods and properties it has at runtime. Reflection is implemented in JavaScript using the for (... in...) statement with the following syntax:
<script type="text/javascript">
// Create 1 Objects myObject As well as 3 Attributes sitename, siteurl, sitecontent .
var myObject = new Object();
myObject.sitename = "sara";
myObject.siteurl = "https://www.ofstack.com/";
myObject.sitecontent = "jb51 Script House ";
// Traversing all properties of an object
for (prop in myObject)
{
document.write(" Attribute '" + prop + "' For " + myObject[prop]);
document.write(" ");
}
</script>
More readers interested in JavaScript can check the topic of this site: javascript Object-Oriented Introduction Tutorial, JavaScript Switching Special Effects and Skills Summary, JavaScript Animation Special Effects and Skills Summary, JavaScript Search Algorithm Skills Summary, JavaScript Data Structure and Algorithm Skills Summary, JavaScript Traversal Algorithm and Skills Summary, json Operation Skills Summary in JavaScript, JavaScript Error and Debugging Skills Summary and JavaScript Mathematical Operation Usage Summary
I hope this article is helpful to everyone's JavaScript programming.