如何在javascript中计算对象

use*_*409 0 javascript

这是我的代码,我想计算这里的对象数量.

使用eval函数我能够获得元素,但不知道如何计算其中的总对象.有人可以帮帮我吗?

var txt = '{
    "employees": [{
        "a": "wkn",
        "d": "Wipro Technologies \u2013 IT Services, Product Engineering Solutions, Technology Infrastructure Services, Business Process Outsourcing, Consulting Services",
        "n": "",
        "u": "http://wipro.com/",
        "t": ["outsourcing", "offshore", "india"],
        "dt": "2009-06-26T10:26:02Z"
    }, {
        "a": "shaktimaan",
        "d": "Wipro Technologies \u2013 IT Services, Product Engineering Solutions, Technology Infrastructure Services, Business Process Outsourcing, Consulting Services",
        "n": "Wipro Technologies is the No 1 provider of integrated business, technology and process solutions on a global delivery platform.",
        "u": "http://wipro.com/",
        "t": ["Indian", "IT", "Services", "Companies"],
        "dt": "2011-09-16T17:31:25Z"
    }, {
        "a": "tonemcd",
        "d": "Offshore Outsourcing | IT Services",
        "n": "",
        "u": "http://wipro.com/",
        "t": ["outsourcing", "IT"],
        "dt": "2007-11-04T03:53:18Z"
    }]
}'; //added \n for readability

var obj = eval ("(" + txt + ")");



document.getElementById("fname").innerHTML=obj.employees[1].a 
document.getElementById("lname").innerHTML=obj.employees[1].u 
Run Code Online (Sandbox Code Playgroud)

这是我得到的回应:

First Name: shaktimaan
Last Name: http://wipro.com/
Run Code Online (Sandbox Code Playgroud)

我能够获取elemtns,但我想要对象计数.

Pav*_*van 8

你可以使用length:

obj.employees.length
Run Code Online (Sandbox Code Playgroud)

这是JSFiddle:http://jsfiddle.net/wavXY/3/

我推荐使用JSON.parse而不是eval.请通过此链接获取更多详细信息:http://www.json.org/js.html