如何将此var a的解析减少到安全的方式,以便在var a不返回或失败时。
var a = "<span style='color:green;'>Speed (NORMAL): 3.36 MB/s</span>";
a = a.split('>');
a = a[1].split(' ');
console.log(a[2]);
输出:
3.36 but its not safe parse cause the a could be empty or null or undefined
目标是:
仅将该值读取为:3.36
如果为空或者未定义/为空等,则应该给出:0
答案 0 :(得分:1)
您可以改为使用正则表达式:
var a = "<span style='color:green;'>Speed (NORMAL): 3.36 MB/s</span>";
a = parseFloat((a.match(/\d+(\.\d+)?/) || '0')[0]);
.match()
返回结果数组或null
,因此,当正则表达式失败时:
(null || '0')[0] = '0'[0] = "0"
进一步阅读: