对于数字,您可以执行 +"10"
而不是 Number("10")
,后者速度更快。有没有办法对字符串中的 boolean 值执行此操作?
最佳答案
使用正则表达式很愚蠢。如果您真的只想匹配字符串 'true'
并且不关心区分大小写,只需与该字符串进行比较:
function parseBoolean(s)
{
return s === 'true';
}
我想如果我真的要和你玩填空游戏,我会回答:
+"10" is to Number("10") as !!"true" is to Boolean("true")
因为 Boolean(x)
仅在 x
为假值时返回 false
,即当 x ∊ {null , undefined, false, 0, ''}
.
关于javascript - 从字符串转换更快的 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8378591/