希望有人能帮忙,因为我对 JS 还很陌生。我需要从 2 个字符串中提取一个数字,然后测试结果是否彼此相等。
例如
var test1 = "7D"
var test2 = "7H"
要提取数字,我使用以下代码,
test1.match(/\d+/) = result in the console is "7",
我对 test2 变量执行同样的操作,结果也是 7。
但是当我使用
测试相等性时test1.match(/\d+/) === test2.match(/\d+/) it evaluates to false.
我尝试在 if 语句中使用此条件,但无法使其工作,例如
if(test1.match(/\d+/) === test2.match(/\d+/)){run some code}
我做错了什么还是有更好的方法来实现这个目标?
谢谢
最佳答案
match
返回一个数组。要比较匹配值,请使用:
var b = (test1.match(/\d+/)[0] === test2.match(/\d+/)[0]);
//=> true
关于javascript - 使用 JS .match() 从字符串中提取数字,然后使用结果来测试相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28916008/