0

这是数组

var weekdayColor = {
        sunday : 'red',       // sunday
        monday : 'blue',      // monday
        tuesday: 'white',     // tuesday
        wednesday: 'black',    
        thursday: 'green',     
        friday: 'yellow',  
        saturday: 'orange'     
    }

我希望能够做一些事情weekcayColor[0]来获得sunday

这是我为面试而写的 JavaScript,已经上交了。我知道有一种更简单的方法可以做到这一点。第一个 varweekdayColor不能更改;也weekdayColor.sunday返回red

也许我使用了错误的日期方法或错误地访问了 var?

var weekdayColor = {
        sunday : 'red',       // sunday
        monday : 'blue',      // monday
        tuesday: 'white',     // tuesday
        wednesday: 'black',     // wednessday
        thursday: 'green',     // thursday
        friday: 'yellow',    // friday
        saturday: 'orange'     // saturday
    }
    var weekday=new Array();
        weekday[0]="sunday";
        weekday[1]="monday";
        weekday[2]="tuesday";
        weekday[3]="wednesday";
        weekday[4]="thursday";
        weekday[5]="friday";
        weekday[6]="saturday";
    d = new Date;
    day = d.getDay();
    console.log(weekday[day]);
    a = weekday[day];
    function change(){
        var x = document.getElementById("weekday");
        x.innerHTML = a;
        x.style.color = weekdayColor[a];
    }
4

2 回答 2

0

更简单的方法是使用如下对象数组:

var weekday = [
   {name:"sunday",color:"red"},
   {name:"monday",color:"blue"},
   // and so on
]

然后你可以做这样的事情:

d = new Date();
day = d.getDay();
weekday[day].name  // yields name
weekday[day].color // yields color

或者,您可以编写一个原型方法:

Date.prototype.getDayName = function() {
return ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
       [this.getDay()];
}

现在

var d = new Date;
d.getDayName(); // this would actually give you the name of the day
于 2013-01-27T20:51:13.407 回答
0

不是 100% 确定您要做什么。如果你只是想改变今天的元素颜色需要修改change()如下:

function change(day){
    var x = document.getElementById(day);       
    x.style.color = weekdayColor[day];
}
var d = new Date(),
    day = d.getDay(),
    a = weekday[day];

/* now call change passing day as argument*/
change(a);

演示:http: //jsfiddle.net/rhHjn/1

于 2013-01-27T20:42:02.737 回答