Is it a bug in Ecmascript - /\S/.test(null) returns true?

后端 未结 2 1119
北荒
北荒 2020-12-06 14:33

Both in Actionscript3 and Javascript these statements give the same result:

/\\S/.test(null) => true  
/null/.test(null) => true  
/m/.test(null) =>         


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 14:51

    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), 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.

    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"]
    

提交回复
热议问题