Access and traversal of JavaScript objects

Source: Internet
Author: User
Tags javascript array

The slave server returns a JSON string with the following content:

var str = [{"id":"328482","user_id":"54","time":"1320214671"},{"id":"328283","user_id":"43","time":"1320046877"},{"id":"327075","user_id":"43","time":"1318740675"},{"id":"326153","user_id":"60","time":"1318144953"}]

Remote links can be referenced in this way. This JSON is an object.

<script src="http://www.bkjia.com/json.php" type="text/javascript"></script>

How can I traverse this JSON object? You can search for a method from the Internet.

Function allPrpos (obj) {// used to save 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 attribute name, obj [p] is the value of the corresponding property props + = p + "=" + obj [p] + "";}} // display all attributes // alert (props); // document. getElementById ("shows "). innerHTML = props ;}

The traversal result is as follows:

0=[object Object] 1=[object Object] 2=[object Object] 3=[object Object] 

You can access the property of an object in this way: str [0] ["id"], because the object is also an object.

There are two methods to directly access the value of property a of object obj:

  • Obj.
  • Obj ["a"]

However, if you use the for/in statement to access the object's property value, you must use the "[]" OPERATOR:

For (m in obj) {alert (obj [m]); alert (obj. m); // undefined} is displayed here}

Why? Because the for/in loop assigns the property name of the object to the variable m as a string.

The javascript array is just a special object, so:

Var arr = new Array (); arr [0] = 10; arr ['a'] = 20; for (m in arr) {alert (m ); // pop up 0 and a alert (arr [m]); // pop up 10 and 20}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.