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

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

看来,空值在这种情况下,转换成字符串空。

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?

推荐答案

这是不是一个错误,但是你是对的,胁迫的到'空'和行为上的规范定义的:

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(字符串) ,内部相当于前pression:<!code> RegExp.prototype.exec(串)= NULL
  2. EXEC 方法类型转换的第一个参数字符串,使用 的ToString 内部操作(看步骤1 EXEC 方法)。
  3. 的ToString 的内部运作,明确地返回当输入是 键入
  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.

总之,在你的例子中,正则表达式配衬对字符串'空',所以第一个非空格字符,在这种情况下,信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天全站免登陆