黄子涵

查漏补缺——说说/^[0-9]+$/.test(time)

问题

如题所示

答案

相关源码:

if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

这里有这样一行代码:

if ((/^[0-9]+$/.test(time)))

查漏补缺——说说/.js$/

正则表达式 /^[0-9]+$/

根据上面,我们可以知道/^[0-9]+$/这是一个正则匹配表达式,/这个符号标志着正则匹配开始,同样也是以这个符号结束。^这个符号标志着字符串的开始,$这个符号标志着字符串的结束,[0-9]表示在0到9这个范围之内,+表示至少出现一次。那么,我们可以得出总结:这是在匹配0到9的数字,这些数字至少出现一次。

test()方法是用来匹配字符串。

那么,我们通过实验看看这个结论正不正确:

function hzh(hzhNum) {
    if((/^[0-9]+$/.test(hzhNum))) {
        console.log("黄子涵");
    } else {
        console.log("黄春钦");
    }
}

console.log("第一次输出:");
hzh(121);
console.log("");
console.log("第二次输出:");
var hcq = "12:34";
hzh(hcq);
console.log("");
console.log("第三次输出:");
hzh("黄子涵");
console.log("");
console.log("第四次输出:");
hzh(hzh);
console.log("");
console.log("第五次输出:");
hzh(31424235252);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
第一次输出:
黄子涵

第二次输出:
黄春钦

第三次输出:
黄春钦

第四次输出:
黄春钦

第五次输出:
黄子涵

[Done] exited with code=0 in 0.267 seconds

实验得出的结果,这个结论是正确。

posted @ 2022-07-01 17:42  黄子涵  阅读(490)  评论(0)    收藏  举报