在Javascript中,知道我可以设置一个数组,以便键是一个自动编号(从0开始)分配的数组:
var d_names = new Array("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday");
// Key for Sunday is '0'
如果我想分配 key ,我可以这样做:
var d_names={};
d_names[5]="Sunday";
d_names[6]="Monday";
d_names[7]="Tuesday";
d_names[8]="Wednesday";
d_names[9]="Thursday";
d_names[10]="Friday";
d_names[11]="Saturday";
// Key for Sunday is '5'
但是,有没有像在PHP中那样分配 key 的简便方法?
var d_names = new Array(5=>"Sunday", 6=>"Monday", 7=>"Tuesday", 8=>"Wednesday",
9=>"Thursday", 10=>"Friday", 11=>"Saturday");
// Doesn't work
最佳答案
您想要的是一个对象:
var d_names = {
5: "Sunday",
6: "Monday"
//...
};
然后,您可以像这样获得
"Sunday"
:var sunday = d_names[5];