M.E*_*Ela 1 javascript calculator
嘿,我正在尝试创建一个计算器,通过在输入中键入一年并单击按钮,可以说明一年中有多少星期五,然后会出现一个警告()
<script>
function Fridaythe13(j) {
var count = document.getElementById('year').value;
var count = 0;
for (var month=0; month<12; month++) {
var d = new Date(j,month,13);
if(d.getDay() == 5){
count++;
}
}
return count;
}
document.getElementById("run").addEventListener("click", function(){
alert(Fridaythe13(count));
})
</script>
<input type="text" name="year" id="year" />
<section class="material">
<div class="actions">
<button type="button" id="run">Run</button>
</div>
</section> Run Code Online (Sandbox Code Playgroud)
当我点击按钮时,它说计数变量没有定义,但我用输入('年')声明它所以我不明白..感谢您提前为您的帮助!
你的一些逻辑被打破了,这是一个有效的例子.
首先,您count在函数中定义了两次变量.
此外,从您的单击处理程序,您将一个参数传递count给您的内部函数,但此变量也未被声明.
考虑为变量使用更好的名称.例如,year而不是j.
也更喜欢使用let/constto var来声明变量.
function fridayThe13(year) {
let count = 0;
for (let month = 0; month < 12; month++) {
const date = new Date(year, month, 13);
if (date.getDay() == 5) {
count++;
}
}
return count;
}
document.getElementById("run").addEventListener("click", () => {
const year = document.getElementById('year').value;
alert(fridayThe13(year));
})Run Code Online (Sandbox Code Playgroud)
<input type="text" name="year" id="year" />
<section class="material">
<div class="actions">
<button type="button" id="run">Run</button>
</div>
</section>Run Code Online (Sandbox Code Playgroud)
这是一个较短的方法,使用函数样式和a map并reduce求值:
function fridayThe13(year) {
return [...Array(12).keys()] // [0, 1, 2,... 11]
.map(month => new Date(year, month, 13).getDay() == 5)
.reduce((accum, val) => accum += val, 0);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
126 次 |
| 最近记录: |