我这里有这个小代码。
var fleet = [];
var number
var Taxi = function(color, badgeNumber) {
this.color = "Yellow";
this.badgeNumber = number;
}
for(var i = 0; i < 5; i++) {
fleet[i] = new Taxi;
number = i;
}
for(var i = 0; i < fleet.length; i++) {
print("Taxi with badge number " + fleet[i].badgeNumber + " is " + fleet[i].color);
}
返回:
Taxi with badge number 4 is Yellow
Taxi with badge number 0 is Yellow
Taxi with badge number 1 is Yellow
Taxi with badge number 2 is Yellow
Taxi with badge number 3 is Yellow
我打算这样做,这个数字会按升序打印出来。显然它应该从0开始。我喜欢尽可能简单,所以问题是我猜为什么不按正确的顺序打印它?
提前谢谢!
答案 0 :(得分:1)
在for循环中打印之前,请使用以下代码对数组进行排序:
fleet.sort(function(a,b){return a.badgeNumber - b.badgeNumber})
答案 1 :(得分:0)
您需要在分配数组之前指定编号。在设置车队后分配编号时,您将获取不是最新的编号并将其分配给徽章编号。执行此操作后,您无需对数组进行排序。
for (var i=0; i < 5; i++)
{
number = i;
fleet[i] = new Taxi;
}
答案 2 :(得分:0)
没有必要再制作另一个for循环。只需编辑你需要的循环,并解决问题。
for(var i = 0; i < 5; i++) {
fleet[i] = new Taxi;
number = i;
print("Taxi with badge number " + fleet[i].badgeNumber + " is " + fleet[i].color);
}
这将始终按顺序打印。
答案 3 :(得分:0)
<html>
<head>
<script>
var fleet = [];
var number;
var Taxi = function(color,badgeNumber)
{
this.color="Yellow";
this.badgeNumber=number;
}
for (var i=0; i < 5; i++)
{
number = i;
fleet[i] = new Taxi;
}
for(var i = 0; i< fleet.length; i++)
{
alert("Taxi with badge number " + fleet[i].badgeNumber + " is " + fleet[i].color);
}
</script>
</head>
</html>