gpt4 book ai didi

javascript - switch语句,不执行任何case

转载 作者:行者123 更新时间:2023-11-29 19:18:23 27 4
gpt4 key购买 nike

我正在尝试编写一个函数来计算已经过去了多少天,并根据该值更新变量并提醒该字符串。

我一直在“未定义”。我的 switch 语句是否正确?

var d = new Date();
var o = new Date(2015, 12, 7);
var todayDate = d.getDate();
var startDate = o.getDate();
var twelveDays = todayDate - startDate;

switch (twelveDays) {
case "0":
var calories = '10';
break;
case "1":
var calories = '20';
break;
case "2":
var calories = '30';
break;
case "3":
var calories = '40';
break;
case "4":
var calories = '50';
break;
case "5":
var calories = '60';
break;
case "6":
var calories = '70';
break;
case "7":
var calories = '80';
break;
case "8":
var calories = '90';
break;
case "9":
var calories = '100';
break;
case "10":
var calories = '110';
break;
case "11":
var calories = '120';
break;
case "12":
var calories = '130';
break;
}

alert(calories);

View on JSFiddle

最佳答案

twelveDays 是一个整数。在您的 switch 语句中,您正在检查一个字符串。没有默认子句,因此它会抛出错误 undefined

像这样改变它:

switch (twelveDays) {
case 0:
var calories = '10';
break;
case 1:
var calories = '20';
break;
case 2:
var calories = '30';
break;
}

此外,添加一个默认子句以防万一是一个好习惯

关于javascript - switch语句,不执行任何case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34186899/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com