Home > Web Front-end > JS Tutorial > body text

JS method example of traversing object properties

高洛峰
Release: 2017-01-14 11:20:18
Original
1513 people have browsed it

The example in this article describes the method of JS traversing object properties. I share it with you for your reference. The details are as follows:

Method to traverse all the attribute names and values ​​of a JavaScript object. This way it is very intuitive and convenient when you want to use the method. The code is as follows:

/*
* 用来遍历指定对象所有的属性名称和值
* obj 需要遍历的对象
* author: Jet Mah
*/
function allPrpos ( obj ) {
// 用来保存所有的属性名称和值
var props = "" ;
// 开始遍历
for ( var p in obj ){
// 方法
if ( typeof ( obj [ p ]) == " function " ){
obj [ p ]() ;
} else {
// p 为属性名称,obj[p]为对应属性的值
props += p + " = " + obj [ p ] + " \t " ;
}
}
// 最后显示所有的属性
alert ( props ) ;
}
Copy after login

AJAX's JavaScript reflection mechanism. The reflection mechanism means that the program can obtain its own information when it is running. For example, an object can know at runtime what methods and properties it has. In JavaScript, the for(…in…) statement is used to implement reflection. The syntax is as follows:

<script type="text/javascript">
// 创建一个对象 myObject 以及三个属性 sitename, siteurl, sitecontent。
var myObject = new Object();
myObject.sitename = "sara";
myObject.siteurl = "http://www.php.cn/";
myObject.sitecontent = "php中文网";
//遍历对象的所有属性
for (prop in myObject)
{
document.write("属性 &#39;" + prop + "&#39; 为 " + myObject[prop]);
document.write(" ");
}
</script>
Copy after login

I hope this article will be helpful to everyone in JavaScript programming.

For more JS method examples of traversing object properties and related articles, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template