请用js代码实现
时间: 2024-02-18 14:01:21 浏览: 16
好的,以下是使用JavaScript实现输入限制的示例代码:
```
function getPositiveInt(prompt) {
while (true) {
let inputStr = prompt(prompt);
if (/^\d+$/.test(inputStr)) {
let num = parseInt(inputStr);
if (num > 0) {
return num;
}
}
alert("请输入正整数!");
}
}
function getInt(prompt) {
while (true) {
let inputStr = prompt(prompt);
if (/^-?\d+$/.test(inputStr)) {
let num = parseInt(inputStr);
return num;
}
alert("请输入整数!");
}
}
let num1 = getPositiveInt("请输入一个正整数:");
console.log("你输入的数是:", num1);
let num2 = getInt("请输入一个整数:");
console.log("你输入的数是:", num2);
```
这里使用了正则表达式来判断用户输入的字符串是否符合要求。`/^\d+$/`表示只能输入数字且必须为正整数,`/^-?\d+$/`表示只能输入数字且可以为负整数。如果用户输入的字符串符合要求,则将其转换为整数并返回;否则提示用户重新输入。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)