[英]Javascript: how to create multidimensional Array?
var mahasiswa = new Array();
mahasiswa[0] = new Array("100000001", "Alda", "man", "1 Mei 1994", "DKV");
mahasiswa[1] = new Array("100000002", "Aldi", "woman", "2 Mei 1994", "Seni");
mahasiswa[2] = new Array("100000003", "Aldo", "man", "3 Mei 1994", "Seni");
mahasiswa[3] = new Array("100000004", "Alfi", "man", "4 Mei 1994", "Akutansi");
mahasiswa[4] = new Array("100000005", "Andi", "man", "5 Mei 1994", "Seni");
mahasiswa[5] = new Array("10000006" , "Bandri","woman", "6 Mei 1994", "DKV");
how I can print name of woman only? 我怎么只能打印女人的名字? The name is at inex
1
(Alda/Aldi etc). 名称为inex
1
(Alda / Aldi等)。
If you don't really need an array, it would be much easier to use an object. 如果您确实不需要数组,则使用对象会容易得多。
Think of an object as a map with key value. 将对象视为具有键值的映射。
var mahasiswa = [];
mahasiswa.push({
id: "100000001",
name:"Alda",
gener: "man",
someDate: "1 Mei 1994
});
mahasiswa.push({
id: "100000001",
name:"Alda",
gender: "woman",
someDate: "1 Mei 1994
});
Then you could use something like this: 然后,您可以使用以下内容:
for(var i=0;i<mahasiswa.length;i++){
var person = mahasiswa[i];
if(person.gender === "woman"){
console.log(mahasiswa[i].name)
}
}
If you really need an Array, then do something like this: 如果确实需要数组,请执行以下操作:
for(i=0; i< mahasiswa.length; i++){
var person = mahasiswa[i];
if(person [2]=='woman'){
console.log(person)
}
}
Some background infos here: 1) If you initialize an array in Javascript, better use this the [] instead of new Array(). 这里有一些背景信息:1)如果用Java初始化数组,最好使用[]而不是new Array()。 It's much faster (See this: http://jsperf.com/literal-vs-new-23 )
它要快得多(请参阅: http : //jsperf.com/literal-vs-new-23 )
2) If possible, use an object over an array. 2)如果可能,请在数组上使用对象。 it's much more flexible
它更加灵活
3) Remember, objects are unsorted where arrays are sorted 3)请记住,对象是未排序的,对数组进行排序
I think the only way is to go through the whole array. 我认为唯一的方法是遍历整个数组。
for(i=0;i<= mahasiswa.length;i++){
if(mahasiswa[i][2]=='woman'){
//...
}
}
otherwise you should rearrange your array and sort it for gender in first dimension. 否则,您应该重新排列数组,并按一维性别对它进行排序。
You can check if the entry is a woman by using this: 您可以使用以下方法检查条目是否为女性:
mahasiswa[n][2] == "woman"
So, using a for loop, you can print out the names of women only: 因此,使用for循环,您只能打印出女性的名字:
for (var i = 0, len = mahasiswa.length; i < len; i++){
if (mahasiswa[i][2] == "woman"){
console.log(mahasiswa[i][1]);
}
}
But normally, in javascript, you wouldn't define an array like this as an array of arrays, but of objects. 但是通常,在javascript中,您不会将像这样的数组定义为由对象而是对象组成的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.