在代码中遇到一些问题。我试图在四个动态文本框中随机播放几周,所以如果今天是星期四其他方块显示星期五和其他星期六,星期日之后的星期日,星期日...而且洗牌时间,但是当它来到星期天我的代码显示null而不是天名, 我哪里做错了?这是一个代码:
var dayOfWeek_array:Array = new Array("Sunday", "Monday", "Tuesday", "Wensday", "Thursday", "Friday", "Saturday");
var today_date:Date = new Date();
var day_str:String = dayOfWeek_array[today_date.getDay()+0];
var day_str1:String = dayOfWeek_array[today_date.getDay()+1];
var day_str2:String = dayOfWeek_array[today_date.getDay()+2];
var tmp1 = today_date.getDay() + 3;
if(tmp1 > 6) tmp -= 7;
var day_str3:String = dayOfWeek_array[tmp];
var tmp = today_date.getDay() + 4;
if(tmp > 6) tmp -= 7;
var day_str4:String = dayOfWeek_array[tmp];
myTextField1.text = (""+day_str1);
myTextField2.text = (""+day_str2);
myTextField3.text = (""+day_str3);
myTextField4.text = (""+day_str4);
答案 0 :(得分:2)
我会指向模运算符:%http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/operators.html#modulo
使用它可以执行dayOfWeek_array[(today_date.getDay()+0) % 7];
这将始终返回0到6之间的数字,因此,您的文本字段中不会出现空值
不同的故事是,我会将您的文本字段放在数组中,因此您可以使用循环来管理它们。有了它,您可以在将来轻松更改字段的行为或数量。
答案 1 :(得分:1)
您应该学习如何重用代码。当索引超出范围时,你没有逻辑逻辑。
以下是如何创建实用程序函数的小示例,它将返回具有offset的数组元素:
var days:Array = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var today:Date = new Date();
//Test
trace(offset(today.day, days)); //Thursday
trace(offset(today.day, days, 1)); //Friday
trace(offset(today.day, days, -1)); //Wednesday
trace(offset(today.day, days, 8)); //Friday
trace(offset(today.day, days, -8)); //Wednesday
function offset(position:int, items:Array, offset:int = 0):Object {
var size:int = items.length;
//Apply offset
position += offset % size;
if (position < 0) {
position += size;
} else if (position >= size) {
position %= size;
}
return items[position];
}