admin管理员组文章数量:1356905
Both in Actionscript3 and Javascript these statements give the same result:
/\S/.test(null) => true
/null/.test(null) => true
/m/.test(null) => false
/n/.test(null) => true
Seems that null value is converted into string "null" in this case.
Is this a known bug in Ecmascript or am I missing something?
Both in Actionscript3 and Javascript these statements give the same result:
/\S/.test(null) => true
/null/.test(null) => true
/m/.test(null) => false
/n/.test(null) => true
Seems that null value is converted into string "null" in this case.
Is this a known bug in Ecmascript or am I missing something?
Share Improve this question edited Mar 12, 2010 at 5:06 YOU 124k34 gold badges190 silver badges222 bronze badges asked Mar 12, 2010 at 4:51 Lauri OherdLauri Oherd 1,4031 gold badge13 silver badges15 bronze badges 1- 8 Pro tip: You will never find a bug in a language or a tool. Only super cool programmers do that. – Marius Commented Mar 12, 2010 at 4:57
2 Answers
Reset to default 11It's not a bug, but you are right, null
coerces to 'null'
and that behavior is defined on the spec:
RegExp.prototype.test(string)
, internally is equivalent to the expression:RegExp.prototype.exec(string) != null
- The
exec
method type converts the first argument to string, using theToString
internal operation (look the Step 1 of theexec
method). - The
ToString
internal operation, explicitly returns"null"
when the input is of typeNull
.
In conclusion, in your examples, the RegExp matchs against the string 'null'
, so the first non-space character, in this case the letter 'n'
.
var a = null+''; // 'null'
/\S/.test(a); // true
(null+'').match(/\S/) // ["n"]
null
is an object, and when testing against objects (non-string), its first converted to string, then its giving you that result.
You could try with /Number/.test(Number)
or /String/.test(String)
, which would return true
too.
Probably String(null)
is being called, which is 'null'
String(Number)
will give
function Number() {
[native code]
}
and /function Number/.test(Number)
return true
too
本文标签: javascriptIs it a bug in EcmascriptStest(null) returns trueStack Overflow
版权声明:本文标题:javascript - Is it a bug in Ecmascript - S.test(null) returns true? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743998084a2573357.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论