简体   繁体   中英

Javascript: How to output array in array with for loop

I´m trying to output the array fields of an array with ist in an Array (More dimensional array). It seems .length does not work in the second array.

Thanks for help!

cheers, toni

<html><head><title>Test</title>
</head><body>
<script type="text/javascript">
var Mitarbeiter = new Array();

Mitarbeiter[0] = new Object();
Mitarbeiter[0]["Name"] = "Hotels";
Mitarbeiter[0]["data"] = new Object();
Mitarbeiter[0]["data"][0] = "Ort 1";
Mitarbeiter[0]["data"][1] = "Ort 2";

Mitarbeiter[1] = new Object();
Mitarbeiter[1]["Name"] = "Restaurants";
Mitarbeiter[1]["data"] = new Object();
Mitarbeiter[1]["data"][0] = "Ort 2";
Mitarbeiter[1]["data"][1] = "Ort 4";



for (var i = 0; i < Mitarbeiter.length; i++) {

document.write("<b>" + i + " : " + Mitarbeiter[i]["Name"] + "</b><br />");

//works
alert (Mitarbeiter[0]["data"][i]);


// works not
for (var f = 0; f < Mitarbeiter[i]["data"].length; f++){
document.write("<br/>&nbsp;" + Mitarbeiter[i]["data"][f]);
}
}
</script>
</body>
</html>
Mitarbeiter[0]["data"] = new Object();

应该

Mitarbeiter[0]["data"] = new Array();

Your "data" fields are Objects (ie property lists or dictionaries) and not arrays, and as such have not length property. The construct

var data = new Object();
data[0] = "Ort 1";
data[1] = "Ort 2";

is identical to

var data = { 0: "Ort 1", 1: "Ort 2" };

Where obviously there is no length to be found.

I would have written the whole thing like this:

var Mitarbeiter = new Array();

Mitarbeiter.push( { 
    Name: "Hotels",
    data: [ "Ort 1", "Ort 2" ]
});

Mitarbeiter.push( {
    Name: "Restaurants",
    data: [ "Ort 2", "Ort 4"] 
});

I think its more concise and easier to understand.

You can create the whole thing in one go using an "object literal":

var Mitarbeiter = [ {
    Name: 'Hotels',
    data: [ 'Ort 1', 'Ort 2' ]
  }, {
    Name: 'Restaurants',
    data: [ 'Ord 2', 'Ort 4' ]
  }
];

Note how the braces indicate the type of object - [ ... ] for a linear array, { ... } for a "normal" Javascript object.

Your data: fields use numeric indices and so should be arrays rather than objects, so use [ ... ] syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM