如何在Javascript中公开来自对象的数据?

时间:2023-01-15 15:40:54

I want to pull the variables of connectData for some debugging. When I do type of I get object back thinking this was an array and I can do connectData[1] I get undefined,

我想拉一些connectData的变量进行一些调试。当我做类型的我得到对象回来认为这是一个数组,我可以做connectData [1]我得到undefined,

So if I want to log out just the host name from connectData can someone please show me an example?

所以如果我想从connectData注销主机名,有人可以给我举个例子吗?

var connectData = {
    hostname: 127.0.0.1,
    port: 1521,
    database: "db", // System ID (SID)
    user: "usename",
    password: "password"
}

3 个解决方案

#1


1  

You can use a for-each loop to iterate through an object's properties.

您可以使用for-each循环来遍历对象的属性。

var connectData = {
    hostname: '127.0.0.1',
    port: '1521',
    database: "db", // System ID (SID)
    user: "usename",
    password: "password"
};

for (var key in connectData) {
    if (connectData.hasOwnProperty(key)) {
        alert(key + " => " + connectData[key]);
    }
}

Working demo: http://jsfiddle.net/Mp6jS/1/

工作演示:http://jsfiddle.net/Mp6jS/1/

#2


2  

This is a javascript object, not an array.

这是一个javascript对象,而不是一个数组。

You can access the individual elements by name. So to log just the hostname, you can do:

您可以按名称访问各个元素。因此,要仅记录主机名,您可以执行以下操作:

console.log(connectData.hostname);

#3


0  

Log it to the console. console.log(connectData)

将其记录到控制台。执行console.log(CONNECTDATA)

In Chrome, you can view the console by right clicking, selecting "Inspect element", and clicking on the "Console" tab.

在Chrome中,您可以通过右键单击,选择“检查元素”,然后单击“控制台”选项卡来查看控制台。

#1


1  

You can use a for-each loop to iterate through an object's properties.

您可以使用for-each循环来遍历对象的属性。

var connectData = {
    hostname: '127.0.0.1',
    port: '1521',
    database: "db", // System ID (SID)
    user: "usename",
    password: "password"
};

for (var key in connectData) {
    if (connectData.hasOwnProperty(key)) {
        alert(key + " => " + connectData[key]);
    }
}

Working demo: http://jsfiddle.net/Mp6jS/1/

工作演示:http://jsfiddle.net/Mp6jS/1/

#2


2  

This is a javascript object, not an array.

这是一个javascript对象,而不是一个数组。

You can access the individual elements by name. So to log just the hostname, you can do:

您可以按名称访问各个元素。因此,要仅记录主机名,您可以执行以下操作:

console.log(connectData.hostname);

#3


0  

Log it to the console. console.log(connectData)

将其记录到控制台。执行console.log(CONNECTDATA)

In Chrome, you can view the console by right clicking, selecting "Inspect element", and clicking on the "Console" tab.

在Chrome中,您可以通过右键单击,选择“检查元素”,然后单击“控制台”选项卡来查看控制台。