它是 Ecmascript 中的错误 -/S/.test(null) 返回 true? [英] Is it a bug in Ecmascript - /S/.test(null) returns true?
本文介绍了它是 Ecmascript 中的错误 -/S/.test(null) 返回 true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Actionscript3 和 Javascript 中,这些语句给出相同的结果:
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
在这种情况下,似乎将空值转换为字符串null".
Seems that null value is converted into string "null" in this case.
这是 Ecmascript 中的已知错误还是我遗漏了什么?
Is this a known bug in Ecmascript or am I missing something?
推荐答案
这不是错误,但你是对的,null
coerces 为 'null'
并且该行为在规范中定义:
It's not a bug, but you are right, null
coerces to 'null'
and that behavior is defined on the spec:
RegExp.prototype.test(string)
,内部等价于表达式:RegExp.prototype.exec(string) != null
exec
方法类型使用ToString
内部操作(看exec
方法的 Step 1).ToString
内部操作,显式当输入为时返回"null"
输入Null
.
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
.
总而言之,在您的示例中,RegExp 与字符串 'null'
匹配,因此第一个非空格字符,在本例中为字母 'n'
.
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"]
这篇关于它是 Ecmascript 中的错误 -/S/.test(null) 返回 true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文