是否正确显示数字表?

问题描述 投票:1回答:1

<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语句,此代码无法正常工作。请告诉我该代码的错误之处。

javascript html function loops switch-statement
1个回答
0
投票

这是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} &times; ${i} = ${value * i}<br>`)
  }
}
<p>Enter a number to get table: </p>
<input id="number" type="text">
<input id="button" type="submit">

了解ifswitch here之间的区别。

© www.soinside.com 2019 - 2024. All rights reserved.