<p>Enter a number to get table: </p>
<input id="number" type="text">
<input type="submit" onclick="tables(number)" >
<script>
const tables = (num) =>{
switch(num.value){
case num.value.match(/[0-9]+$/):
for (var i = 1; i<= 10; i++){
document.write(`${num.value} * ${i} = ${num.value * i}<br>`)
}
break;
default:
return alert(`Invalid Entry!`)
break;
}
}
我想显示输入数字表,但是通过使用switch语句,此代码无法正常工作。请告诉我该代码的错误之处。
这是if
语句的经典用例:
const input = document.getElementById('number')
const button = document.getElementById('button')
button.addEventListener('click', tables)
function tables() {
const value = input.value
if (null === value.match(/^[0-9]+$/)) {
// if the value doesn't only consist of numeric symbols
// alert a message and return (stop executing the function)
alert(`Invalid Entry!`)
return
}
// if the user input is valid, proceed with the output
for (let i = 1; i <= 10; i++) {
document.write(`${value} × ${i} = ${value * i}<br>`)
}
}
<p>Enter a number to get table: </p>
<input id="number" type="text">
<input id="button" type="submit">
了解if
和switch
here之间的区别。