gpt4 book ai didi

javascript - 对字符串执行简单的数字测试

转载 作者:行者123 更新时间:2023-11-30 10:25:49 25 4
gpt4 key购买 nike

我刚刚开始我的编程之旅,最近我一直在大学学习如何使用 JavaScript。我被困在一个我无法理解的练习上!

问题是:在不使用逻辑运算符 [提示:字符串运算符] 的情况下编写数字测试。

所以我需要一个测试,看看字符串中是否有任何数字。我已经做到了:

var x=prompt("请输入任意字符"); (例如 hello123)

var y="0123456789";

(我认为输入应该以某种方式与 y 变量进行比较,这样我才能得到答案)

这就是我的全部!希望这不会太复杂。 (等不及那个“哦耶..”的时刻了!)

最佳答案

我不太确定你的问题的确切界限是什么,但你可以使用正则表达式来检查数字:

var x = prompt("Enter any characters");
if (x && x.match(/\d/)) {
// there are digits in the string
}

或以不同的方式编写(均有效):

var x = prompt("Enter any characters");
if (x && /\d/.test(x)) {
// there are digits in the string
}

请注意,这也是在尝试将其用作字符串之前确保 x 非空且不为空,因为如果用户取消提示,它将返回 null.

正则表达式中的

\d表示匹配任意数字

您可以阅读 javascript here 中的正则表达式以及使用它们的字符串方法 here


我还在猜测你的问题的真正界限是什么,但是如果没有正则表达式并且只使用你在评论中提到的函数,你可以这样做:

var digits = "0123456789";

// get string from user
var str = prompt("Enter any characters");

// check each digit one at a time
if (str) {
for (var i = 0; i < digits.length; i++) {
// see if the next digit is in the string
if (str.indexOf(digits.charAt(i)) {
// found a digit
}
}
}

关于javascript - 对字符串执行简单的数字测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19611827/

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