获取day text函数返回undefined

时间:2015-12-31 10:38:26

标签: javascript jquery

不确定下面我的函数的逻辑缺陷在哪里,我正在尝试以字符串形式获取day值。

function getDayText(date){
        var weekday = new Array(7);

        weekday[0]=  "Sunday";
        weekday[1] = "Monday";
        weekday[2] = "Tuesday";
        weekday[3] = "Wednesday";
        weekday[4] = "Thursday";
        weekday[5] = "Friday";
        weekday[6] = "Saturday";

        return weekday[date];
}

console.log(getDayText(2016-1-1)) // undefined

4 个答案:

答案 0 :(得分:2)

问题是您的参数2016-1-1不是有效日期。

//no need to create array for each call
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

var day = function(str) {
  var tmp = new Date(str); //create date
  return days[tmp.getDay()];
};

alert(day('2016-1-1')); //<-- note, its string

答案 1 :(得分:1)

以下内容:

console.log(getDayText(2016-1-1));

与:

相同
console.log(getDayText(2014));

但是您的weekday数组只有7个元素,而不是2014年。因此,当您尝试访问此数组的第2014个元素时,获得undefined是正常的。确保仅指定有效索引(在您的情况下,从0到6)。例如:

console.log(getDayText(3));

答案 2 :(得分:0)

您需要通过一周中的某一天才能获得预期的结果。

console.log(getDayText(new Date("2016-1-1").getDay()));

答案 3 :(得分:0)

您可能想要使用Date。将您的日期作为(有效)字符串传递给它的构造函数,并使用getDay方法获取星期几。

&#13;
&#13;
function getDayText(date){
	var weekday = new Array(7);

	weekday[0]=  "Sunday";
	weekday[1] = "Monday";
	weekday[2] = "Tuesday";
	weekday[3] = "Wednesday";
	weekday[4] = "Thursday";
	weekday[5] = "Friday";
	weekday[6] = "Saturday";

	return weekday[new Date(date).getDay()];
}

document.write('<pre>' + getDayText("2016-01-01") + '</pre>');
&#13;
&#13;
&#13;

我更喜欢将Date对象传递给您的方法而不是字符串,所以要整理它:

&#13;
&#13;
function getDayText(date) {
  var days = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
  ];
  return days[date.getDay()];
}

document.write('<pre>' + getDayText(new Date("2016-01-01")) + '</pre>');
&#13;
&#13;
&#13;