它是 Ecmascript 中的错误 -/S/.test(null) 返回 true? [英] Is it a bug in Ecmascript - /S/.test(null) returns true?

查看:22
本文介绍了它是 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:

  1. RegExp.prototype.test(string),内部等价于表达式:RegExp.prototype.exec(string) != null
  2. exec 方法类型使用 ToString 内部操作(看 exec 方法的 Step 1).
  3. ToString 内部操作,显式当输入为时返回 "null"输入 Null.
  1. RegExp.prototype.test(string), internally is equivalent to the expression: RegExp.prototype.exec(string) != null
  2. The exec method type converts the first argument to string, using the ToString internal operation (look the Step 1 of the exec method).
  3. The ToString internal operation, explicitly returns "null" when the input is of type Null.

总而言之,在您的示例中,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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆