像数组一样使用JavaScript对象值

Using JavaScript Object values like an array

本文关键字:JavaScript 对象 一样 数组      更新时间:2023-09-26

我对JavaScript世界相当陌生,我不完全确定如何使用对象,就像它是一个数组一样(通过索引而不是特定的名称从对象内部访问信息)。

我想检索一个对象的内容的值基于它的索引,类似于数组。下面的代码说明了这一点:

function pieChart(daten, width, height, div)
{
    var data = new google.visualization.DataTable();
    
    data.addColumn('string');
    data.addColumn('number');
    //returns: [Object, Object, Object, Object]
    console.log(daten);
    for(item in daten)
    {    
         console.log(daten[item]);
         //The following 4 lines are the output of the console log
         //Object {crimes: "300", location: "Cardiff"}
         //Object {crimes: "900", location: "London"}
         //Object {crimes: "500", location: "Manchester"}
         //Object {crimes: "400", location: "Dublin"}             
        
         //here in lies the problem...
         data.addRow([daten[item].location, parseInt(daten[item].crimes)]);
         //the output would be: ["Dublin", 400] etc...
    }
    var chart = new google.visualization.pieChart(document.getElementById(div));
    chart.draw(data, {"width": width, "height": height});
}

本质上,我希望能够执行data.addRow([daten[item][0], daten[item[1]]),因为我不知道运行时的位置和犯罪。

编辑:

我应该注意到,我使用谷歌可视化API(如上所示),它接受一个数组作为data.addRow()的值。因此,一个可能的解决方案是将对象转换为具有上述指定要求的数组,使输出为:["Dublin", 400]["London", 900]["Manchester", 500]["Cardiff", 300]。然而,我不确定如何去做这件事。

不能这样访问对象属性。知道索引的名称;这就是它们的基本工作原理。我想你可以做你想做的,但是,通过迭代对象的属性。这样,您就不需要事先知道属性的名称:

var rowData = [];
for(var property in daten[item]) {
    var value = daten[item][property];
    //Since you want to convert some strings to integers, this
    //regex checks to see if the value is an integer or not
    if(/^-?'d+$/.test(value)) {
        rowData.push(parseInt(value, 10))   
    } else {
        rowData.push(value);
    }
}
data.addRow(rowData);

注意:请记住,这并不能为daten[item]中的键提供可预测的顺序。

应该通过键来访问对象的值:

data.addRow(item.location, item.crimes);

您可以通过以下方式访问该值daten[item][location]